|
Today, in the programming, you need to use to store and transfer data Hashmap, he found himself learning Java so long, in fact, generics are still poorly understood, search tidied HashMap use.
HashMap declaration initialized because generic reasons, from the two key and value parameters are required for specific types of methods can be put to use to transfer data to a HashMap,
HashMap data = new HashMap ();
data.put ( "Apple", 100);
data.put ( "pear", 200);
data.put ( "grape", 300);
data.put ( "banana", 400);
data.put ( "lychee", 500);
HashMap using my degree is its focus traversal algorithm ,, its traversal algorithm there are two, and you can use KeySet entrySet to traverse, the core code is as follows:
The first: using EntrySet
Map map = new HashMap ();
Iterator iter = map.entrySet () iterator ().;
while (iter.hasNext ()) {
Map.Entry entry = (Map.Entry) iter.next ();
Object key = entry.getKey ();
Object val = entry.getValue ();
}
High efficiency, it will be easy to use in this way!
The second: use the KeySet
Map map = new HashMap ();
Iterator iter = map.keySet () iterator ().;
while (iter.hasNext ()) {
Object key = iter.next ();
Object val = map.get (key);
}
Some team is inefficient, in this way it has the advantage that it can be worth based on what you want you want to key values, more flexibility! !
The two ways to traverse fact there is a difference, for keySet actually traversed twice, once into iterator, once to remove the key from the hashmap for the value.
The entryset just traversing the first, it is the key and value are placed in the entry, so fast. |
|
|
|