简体   繁体   中英

Key in HashMap java

I usually come across scenarios while using HashMap in Java as follows :

I've a list of Objects of class A ( List<A> )
A has fields int f1, int f2 and other fields.

I've to construct a map from List to perform O(1) lookup for the Objects of A. The key is combination of f1 and f2 (both being integers).

Now which of the following would be the best practice to use for the map
case 1 : in general
case 2 : f2 can take only 2 to 3 different values, while f1 can take large number of values.

Map<Integer, Map<Integer, List<A>>>  // construction of map is cumbersome
Map<String, List<A>>                 //(key : String f1 + "_" + f2)
Map<Integer, List<A>>          //(I tend to use this for case 2)

Missed to clarify one thing here. f1 and f2 don't uniquely identify objects of A. Corrected the map definitions.

If those two fields tend to be immutable (they don't change once set), you can override the equals() and hashCode() methods of A, and simply store a:

Set<A>    //(key: fields f1 and f2, via hashCode() method)

If they are not immutable, you cannot use them for the key anyway, since they might change.

我认为Map适合案例1,对于案例,我建议使用List,并且此列表仅包含2-3个元素,然后可以将索引映射到特定字段值。

Why use a map at all? If you don't really need Key-Value pairs, you can just use a HashSet<A> . The lookup is still O(1) and you don't have to bother getting a value from the key.

Of course, the HashSet is probably just a HashMap with null values, but you don't have to invent keys and values.

I don't like using Strings as composite keys. Some blogger out there put it well: Strings are good for things that are text, and not good for things that aren't text.

Why not just create a simple IntPair class with two int fields, and appropriate hashCode() and equals(Object) overrides? It'll take you two seconds in an IDE (not much longer without one), and you'll have a more specific, semantically meaningful key type.

Key is unique in HashMap...because internally in java key is set as

final Key

int static Entry class in java

That's why the key is unique it won't allow duplicates...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM