< prev index next >

src/java.base/share/classes/java/lang/String.java

Print this page

        

@@ -34,10 +34,11 @@
 import java.util.Formatter;
 import java.util.Locale;
 import java.util.Objects;
 import java.util.Spliterator;
 import java.util.StringJoiner;
+import java.util.function.ToIntFunction;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.regex.PatternSyntaxException;
 import java.util.stream.IntStream;
 import java.util.stream.StreamSupport;

@@ -1227,15 +1228,28 @@
      * @see     java.text.Collator
      * @since   1.2
      */
     public static final Comparator<String> CASE_INSENSITIVE_ORDER
                                          = new CaseInsensitiveComparator();
+
+    /**
+     * A hashCode computing function that is consistent with
+     * {@link #CASE_INSENSITIVE_ORDER} {@code Comparator}.
+     *
+     * @since 9
+     */
+    @SuppressWarnings("unchecked")
+    public static final ToIntFunction<String> CASE_INSENSITIVE_HASHER
+        = (ToIntFunction<String>) CASE_INSENSITIVE_ORDER;
+
     private static class CaseInsensitiveComparator
-            implements Comparator<String>, java.io.Serializable {
+            implements Comparator<String>, java.io.Serializable,
+                       ToIntFunction<String> /* hasher */ {
         // use serialVersionUID from JDK 1.2.2 for interoperability
         private static final long serialVersionUID = 8575799808933029326L;
 
+        @Override
         public int compare(String s1, String s2) {
             byte v1[] = s1.value;
             byte v2[] = s2.value;
             if (s1.coder() == s2.coder()) {
                 return s1.isLatin1() ? StringLatin1.compareToCI(v1, v2)

@@ -1243,10 +1257,19 @@
             }
             return s1.isLatin1() ? StringLatin1.compareToCI_UTF16(v1, v2)
                                  : StringUTF16.compareToCI_Latin1(v1, v2);
         }
 
+        /**
+         * Compute hashCode consistent with {@link #compare(String, String)}
+         */
+        @Override
+        public int applyAsInt(String s) {
+            return s.isLatin1() ? StringLatin1.hashCodeCI(s.value)
+                                : StringUTF16.hashCodeCI(s.value);
+        }
+
         /** Replaces the de-serialized object. */
         private Object readResolve() { return CASE_INSENSITIVE_ORDER; }
     }
 
     /**
< prev index next >