Reputation: 207
In http://docs.oracle.com/javase/7/docs/api/java/util/Map.html I see 19 classes that implement the Map interface. Which one should I use? I want to map integers to integers. I would use Array but I see HashMap in many example, so I am thinking about:
Map<Integer, Integer> myMap = Collections.synchronizedMap(new HashMap<Integer, Integer>());
Basically I want to simulate the less strict arrays that I can find on other languages like PHP where I can asign any integer to any value without caring about fixed lengths or using lists.
Upvotes: 0
Views: 75
Reputation: 12206
If you're not concerned about thread-safety, just use Hashmap<Integer, Integer>
. If multiple threads will be accessing the map, then ConcurrentHashMap is probably your best choice. See thread safe map for java for more details.
Upvotes: 1
Reputation: 272217
Your simplest and most straightforward option is to use a HashMap<Integer, Integer>()
. You don't have to worry about threading, or paying for any performance penalty whilst sorting (as you would with TreeMap
) etc.
You also ask about threading. Note that HashMap itself isn't thread safe, and simultaneous operations on it will blow up (e.g. maps do internal state changes like resizing upon puts, and a simultaneous put will likely fail). So a ConcurrentHashMap
will likely be required. However note that you may need to still synchronise around that object if you're performing multiple atomic operations e.g.
if (!map.contains(key)) {
map.put(key, ...);
}
Upvotes: 1
Reputation: 3684
You can simply use HashMap
or MultiHashMap
ref from apache, dependent on your project requirements. Synchronized collections from Collections.synchronized*
are slower than normal collections. So basically if you will not use that collection in multithreading environment you should avoid synchronized collections for basuc one thread stuff because they are simply slower.
Upvotes: 1