10

org.apache.myfaces.trinidad.util.ArrayMap和的主要区别是什么java.util.HashMap

ArrayMap 是线程安全的吗?

在文档中提到 Array 在性能方面是最好的。

我不想使用 hashmap 或并发 hashmap。我想试试下面的其他。如果我考虑线程安全和性能,哪一个是最好的选择?

ArrayMap<String,String> var= new ArrayMap<String,String>(); 
4

1 回答 1

-1

HashMap uses an array underneath so it can never be faster than using an array correctly.

Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.The reason your array is so slow is due to the equals comparisons, not the array access itself.

An ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.

List:

An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Map:

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

The list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background. You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).

The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarantee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).

When to use Arrays?

Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.

Sometimes, it may be best to use a combination of the above approaches. For example, you could use a ArrayList of HashMap to suit a particular need.

于 2013-10-18T05:41:22.190 回答