Home > Back-end >  Can I hashCode() an ArrayList of Strings?
Can I hashCode() an ArrayList of Strings?

Time:12-02

Say I have a string array String[] array1; Then I can get its hash value like so : Arrays.hashCode(array1); But if I use an arraylist of strings I get a compilation error : List<String> array2 = new ArrayList<String>(); int res = Arrays.hashCode(array2); (https://i.stack.imgur.com/rTJrn.png)](https://i.stack.imgur.com/rTJrn.png) Is there any way i can get around this?

I tried deepHashCode() which VS Code recommended but that didn't seem to work either

CodePudding user response:

Arrays.hashCode expects an array. Arrays.asList returns a List<T>.

List already provides its own implementation of hashCode:

List<String> array2 = new ArrayList<String>();
int res = array2.hashCode();

The implementation of both methods is mostly identical:

java.util.Arrays#hashCode(Objects[]):

    public static int hashCode(Object[] a) {
        if (a == null)
            return 0;

        int result = 1;

        for (Object element : a)
            result = 31 * result   (element == null ? 0 : element.hashCode());

        return result;
    }

java.util.AbstractList#hashCode():

    public int hashCode() {
        int hashCode = 1;
        for (E e : this)
            hashCode = 31*hashCode   (e==null ? 0 : e.hashCode());
        return hashCode;
    }
  • Related