0

I tried the following code so far, and it does not work.

HashMap<long, HashSet<long>> hm = new HashMap<>();

I know the reason is long is not reference, and we need reference type. Any comments are greatly appreciated.

qaz
  • 35
  • 6

3 Answers3

4

Its better use it like:
Map<Long, HashSet<Long>> hm = new HashMap<Long, HashSet<Long>>();

Always remember that Java Generics is used to work with Object and thier methods, so no premetive types are allowed.

roeygol
  • 4,908
  • 9
  • 51
  • 88
0

You cannot use primitives as a Generic type parameter as they are compile time constructs that need to be cast to the appropriate Java type.

Refer to: Why don't Java Generics support primitive types?

Community
  • 1
  • 1
Khanna111
  • 3,627
  • 1
  • 23
  • 25
0

You need to use Objects as keys. long is primitive not an Object.

The reason a Hashmap works with lookup speed of almost O(1) is that when you call put method it computes a hashcode of key and compresses that and based on that puts that in an specific index of an array of Linkedlists. Then when you call get method it quickly does the calculation again (based on key) and finds the right index in the array which mentioned. So keys should be objects and hopefully with a good hashcode implementation. For example here you should use Long object instead of long primitive. For more info look at: How does a Java HashMap handle different objects with the same hash code? http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html

Community
  • 1
  • 1
Hamed Moghaddam
  • 564
  • 3
  • 8