Joe Darcy wrote:
Joe Darcy wrote:
Stephen Colebourne wrote:
Joe Darcy wrote:
What other utility methods would have broad enough use and applicability to go into a common java.util class?

Joe,
You've asked for a call for ideas, but not given any indication of process. Are you going to evaluate everything that comes in and pick the best a la Coin? Or allow anyone to send in patches?

Those options are not mutually exclusive; patches are welcome subject to the usual terms and conditions.

Who decides what is in and what is out?

This is a little side project of mine and I wanted to get some feedback before preparing a formal change for review, possibly including patches from others.

-Joe

I'm getting caught up after the JVM Languages Summit and will post some java.util.Objects code for review in the near future.

-Joe

Below is a patch implementing the methods I think should go into java.util.Objects as a first cut:

* null safe two-argument equals method
* null safe hashCode(Object) returning 0 for null
* null safe toString(Object), returning "null" for a null argument
* null tolerating compare method; tests if both arguments are == and if not calls compare

The need for the last of these in Objects isn't quite as clear.

Var-arg-ifying some of the existing methods in Arrays, (hashCode(Object[]), deepHashCode(Object[]) and toString(Object[])), is probably worthwhile but can be done separately.

I wouldn't oppose a toDebugString(Object) method going into the platform somewhere, but I don't think it necessarily belongs in Objects.

Further below is the code for an annotation processor which finds candidate equals methods to be replaced with Objects.equals. It found over half a dozen good candidates in the jdk repository. To run the annotation processor, first compile the class and then run it with javac similar to this:

javac -proc:only -processor EqualsFinder -processorpath <path to processor> sources

-Joe

--- old/make/java/java/FILES_java.gmk    2009-10-01 21:04:12.000000000 -0700
+++ new/make/java/java/FILES_java.gmk    2009-10-01 21:04:12.000000000 -0700
@@ -258,6 +258,7 @@
    java/util/ServiceConfigurationError.java \
    java/util/Timer.java \
    java/util/TimerTask.java \
+    java/util/Objects.java \
    java/util/UUID.java \
    java/util/concurrent/AbstractExecutorService.java \
    java/util/concurrent/ArrayBlockingQueue.java \
--- /dev/null    2009-08-12 17:12:33.000000000 -0700
+++ new/src/share/classes/java/util/Objects.java 2009-10-01 21:04:13.000000000 -0700
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Sun designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Sun in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+package java.util;
+
+/**
+ * This class consists of {...@code static} utility methods for operating
+ * on objects.
+ */
+public class Objects {
+    private Objects() {
+ throw new AssertionError("No java.util.Objects instances for you!");
+    }
+
+    /**
+     * Returns {...@code true} if the arguments are equal to each other
+     * and {...@code false} otherwise.
+     * Consequently, if both arguments are {...@code null} {...@code true}
+     * is returned and if exactly one argument is {...@code null} {...@code
+     * false} is returned.  Otherwise, equality is determined by using
+     * the {...@link Object#equals equals} method of the first
+     * argument.
+     *
+     * @return {...@code true} if the arguments are equal to each other
+     * and {...@code false} otherwise
+     * @see Object#equals(Object)
+     * @since 1.7
+     */
+    public static boolean equals(Object a, Object b) {
+        return (a == b) || (a != null && a.equals(b));
+    }
+
+    /**
+     * Returns the hash code of a no...@code null} argument and 0 for
+     * a {...@code null} argument.
+     *
+     * @return the hash code of a no...@code null} argument and 0 for
+     * a {...@code null} argument
+     * @see Object#hashCode
+     * @since 1.7
+     */
+    public static int hashCode(Object o) {
+        return o != null ? o.hashCode() : 0;
+    }
+
+    /**
+     * Returns the result of calling {...@code toString} for a no...@code
+     * null} argument and {...@code "null"} for a {...@code null} argument.
+     *
+     * @return the result of calling {...@code toString} for a no...@code
+     * null} argument and {...@code "null"} for a {...@code null} argument
+     * @see Object#toString
+     * @since 1.7
+     */
+    public static String toString(Object o) {
+        return (o != null) ? o.toString() : "null" ;
+    }
+
+    /**
+     * Returns 0 if the arguments are identical and {...@code
+     * c.compare(a, b)} otherwise.
+     * Consequently, if both arguments are {...@code null} 0
+     * is returned.
+     *
+     * @return 0 if the arguments are identical and {...@code
+     * c.compare(a, b)} otherwise.
+     * @see Comparable
+     * @see Comparator
+     * @since 1.7
+     */
+    public static <T> int compare(T a, T b, Comparator<? super T> c) {
+        return (a == b) ? 0 :  c.compare(a, b);
+    }
+}
--- /dev/null    2009-08-12 17:12:33.000000000 -0700
+++ new/test/java/util/Objects/BasicObjectsTest.java 2009-10-01 21:04:14.000000000 -0700
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
+ * CA 95054 USA or visit www.sun.com if you need additional information or
+ * have any questions.
+ */
+
+
+/*
+ * @test
+ * @bug 6797535
+ * @summary Basic tests for methods in java.util.Objects
+ * @author  Joseph D. Darcy
+ */
+
+import java.util.*;
+
+public class BasicObjectsTest {
+    public static void main(String... args) {
+        int errors = 0;
+        errors += testEquals();
+        errors += testHashCode();
+        errors += testToString();
+        errors += testCompare();
+        if (errors > 0 )
+            throw new RuntimeException();
+    }
+
+    private static int testEquals() {
+        int errors = 0;
+        Object[] values = {null, "42", 42};
+ + for(int i = 0; i < values.length; i++)
+            for(int j = 0; j < values.length; j++) {
+                boolean expected = (i == j);
+                Object a = values[i];
+                Object b = values[j];
+                boolean result = Objects.equals(a, b);
+                if (result != expected) {
+                    errors++;
+ System.err.printf("When equating %s to %s, got %b intead of %b%n.",
+                                      a, b, result, expected);
+                }
+            }
+        return errors;
+    }
+
+    private static int testHashCode() {
+        int errors = 0;
+        errors += (Objects.hashCode(null) == 0 ) ? 0 : 1;
+        String s = "42";
+        errors += (Objects.hashCode(s) == s.hashCode() ) ? 0 : 1;
+        return errors;
+    }
+
+    private static int testToString() {
+        int errors = 0;
+        errors += ("null".equals(Objects.toString(null)) ) ? 0 : 1;
+        String s = "Some string";
+        errors += (s.equals(Objects.toString(s)) ) ? 0 : 1;
+        return errors;
+    }
+
+    private static int testCompare() {
+        int errors = 0;
+        String[] values = {"e. e. cummings", "zzz"};
+        String[] VALUES = {"E. E. Cummings", "ZZZ"};
+ + errors += compareTest(null, null, 0); + + for(int i = 0; i < values.length; i++) {
+            String a = values[i];
+            errors += compareTest(a, a, 0);
+            for(int j = 0; j < VALUES.length; j++) {
+                int expected = Integer.compare(i, j);
+                String b = VALUES[j];
+                errors += compareTest(a, b, expected);
+            }
+        }
+        return errors;
+    }
+
+    private static int compareTest(String a, String b, int expected) {
+        int errors = 0;
+        int result = Objects.compare(a, b, String.CASE_INSENSITIVE_ORDER);
+        if (Integer.signum(result) != Integer.signum(expected)) {
+            errors++;
+ System.err.printf("When comaping %s to %s, got %d intead of %d%n.",
+                              a, b, result, expected);
+ + }
+        return errors;
+    }
+}


/*
* Copyright 2009 Sun Microsystems, Inc.  All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.util.Set;
import java.util.EnumSet;

import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import static javax.lang.model.SourceVersion.*;
import static javax.lang.model.element.Modifier.*;
import static javax.lang.model.element.ElementKind.*;
import static javax.lang.model.type.TypeKind.*;
import static javax.lang.model.util.ElementFilter.*;
import static javax.tools.Diagnostic.Kind.*;

@SupportedAnnotationTypes("*")     // Process (check) everything
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public class EqualsFinder extends AbstractProcessor {
   private EqualsFinder0 equalsFinder;

   public EqualsFinder() {super();}
@Override
  public boolean process(Set<? extends TypeElement> annotations,
                         RoundEnvironment roundEnv) {
       if (!roundEnv.processingOver()) {
           for (Element element : roundEnv.getRootElements() )
               equalsFinder.find(element);
       }
       return false; // Allow other processors to examine files too.
   }

   @Override
   public void init(ProcessingEnvironment processingEnv) {
       super.init(processingEnv);
       equalsFinder = new EqualsFinder0(processingEnv);
   }


   private static class EqualsFinder0 {
       private final Messager messager;
       private final Elements eltUtils;

       EqualsScanner equalsScanner = new EqualsScanner();

       EqualsFinder0(ProcessingEnvironment processsingEnv) {
           this.messager  = processsingEnv.getMessager();
           this.eltUtils = processsingEnv.getElementUtils();
       }
public void find(Element e) {
           equalsScanner.scan(e);
       }

       /**
        * Visitor to implement name checks.
        */
      private class EqualsScanner extends ElementScanner6<Void, Void> {

           /**
            * Check the name of an executable (method, constructor,
            * etc.) and its type parameters.
            */
           @Override
           public Void visitExecutable(ExecutableElement e, Void p) {
               // Check the name of the executable
               if (e.getKind() == METHOD) {
                   Name name = e.getSimpleName();
                   if (name.contentEquals("equals") &&
                       e.getModifiers().contains(Modifier.STATIC) &&
                       e.getParameters().size() == 2)  {
messager.printMessage(NOTE, "Possible Objects.equals replacement.", e); eltUtils.printElements(new java.io.OutputStreamWriter(System.out) , e);
                   }
               }
               return null;
           }
      }
   }
}

Reply via email to