5

Why is ArrayList in Java hashable and List in Python not. It's just based on the choice of the developers or language semantics.

I think Python doesn't allow list to be hashable because it's mutable and hence the hash can change over the lifetime of the object.

It's a good feature or bad feature why does Java allow it.

public class Test {

    public static void main(String[] args) {


        ArrayList<String> list = new ArrayList<String>();

        list.add("hello");

        System.out.println(list.hashCode());

    }

}

works fine while below doesn't

>>> l = ["hello"]
>>> l.__hash__()

Traceback (most recent call last):
  File "<pyshell#103>", line 1, in <module>
    l.__hash__()
TypeError: 'NoneType' object is not callable
2
  • Please let us know why the down vote Commented Nov 29, 2015 at 1:18
  • 2
    I tried editing your question to make it less random and vague. Don't blame me for further downvotes. Commented Nov 29, 2015 at 1:18

1 Answer 1

4

You are correct that Lists in Python are not hashable because Python does not permit mutable data to be keys to dictionaries.

Java ArrayLists are hashable because Java, one, does not have any language-level support for immutability, and two forces all objects to be hashable. Whether the hash is "useful" depends on the class's implementation.

I think the "story" is simply that Python has language-level support for dictionaries and has made some design decisions around this, while Java does not.

While Python is "weakly typed" for some definition of "weakly," you should not infer that Python is the Wild West of programming languages where everything goes with no built-in safety. That would be Perl or Javascript.

Sign up to request clarification or add additional context in comments.

10 Comments

I don't understand what you mean by language level support, dictionaries are there in Java also.
@User is it a java 8 feature? if so then change my answer to say "Through Java 7," if not then no there isn't.
Python is strongly typed.
@User dictionaries are part of the language in Python (e.g. kwargs). Java has HashMap and Hashtable, but these are just classes. There is no special syntax or language feature which requires them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.