Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not create a HashMap with 'long' types in Java?

Tags:

java

hashmap

Any reason that the following is not allowed?

HashMap<long, long> x = new HashMap<>();
like image 229
Kumar Vaibhav Avatar asked Nov 30 '14 08:11

Kumar Vaibhav


3 Answers

you're using primitives rewrite to HashMap<Long,Long> x = new HashMap<>()

like image 51
Master Slave Avatar answered Nov 12 '22 16:11

Master Slave


In Java, types with generic type parameters, such as HashMap, only accept types that inherit from Object. long does not inherit from Object, so you can't use it with HashMap. You can however use Long, which is a boxed version of long.

like image 39
KeyboardDrummer Avatar answered Nov 12 '22 17:11

KeyboardDrummer


Using standard collections for primitive types like long is not really effective

If you need to minimize memory footprint and get better performance you should consider 3rd-party collection libraries like Trove

like image 34
bedrin Avatar answered Nov 12 '22 17:11

bedrin