The HashMap class makes use of a hash desk to implement the Map interface. This enables the execution time of fundamental operations, resembling get() and put(), to stay fixed even for big units. HashMap implements Map and extends AbstractMap. It doesn’t add any strategies of its personal.
As soon as ought to notice following options of HashMap as compair to different collections.
- HashMap doesn’t assure the order of its components.The order through which components are added to a hash map just isn’t essentially the order through which they’re learn by an iterator.
- HashMap just isn’t synchronized, this makes HashMap higher for non-threaded purposes, as unsynchronized Objects sometimes carry out higher than synchronized ones.An equivalently synchronised HashMap could be obtained by:
Collections.synchronizedMap(myMap)
- HashMap permits one null key and any variety of null values.
- HashMap’s subclass LinkedHashMap with predictable iteration order (which is insertion order by default), this implementation differs from HashMap.
Let’s see how we Iterate HashMap
utilizing for-each loop in java. I’m creating a category Tackle which is a member variable of Consumer
class. Following code exhibits Tackle
class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import static java.lang.String.format;
import static java.lang.System.out;
class Tackle {
personal String avenue,metropolis;
public Tackle(){}
public Tackle(String avenue, String metropolis){
this.avenue=avenue;
this.metropolis=metropolis;
}
@Override public String toString(){
return format(“Road: %s, Metropolis: %s”,avenue,metropolis);
}
}
|
and Consumer
class…
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
import static java.lang.String.format;
import static java.lang.System.out;
class Consumer {
personal String title, pwd;
personal Tackle deal with;
public Consumer(){}
public Consumer(String title, String pwd, Tackle deal with){
this.title=title;
this.pwd=pwd;
this.deal with=deal with;
}
public String getName(){return this.title;}
public String getPwd(){return this.pwd;}
public Tackle getAddress(){return this.deal with;}
@Override public String toString(){
return format(“Identify: %s, Pwd: %s”,title,pwd);
}
}
|
Put Consumer
objects in HashMap
and iterate utilizing for-each loop. First we’re changing Map into Set utilizing entrySet()
methodology, foreach loop go to every Entry
out there and return Entry
in each go to.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import static java.lang.String.format;
import static java.lang.System.out;
public class MapIterationTest {
public static void primary(String s[]) {
Map<Integer,Consumer> customers = new HashMap<Integer,Consumer>();
customers.put(23, new Consumer(“asif”,“ask!@#”, new Tackle(“shani peth”,“jalgaon”)));
customers.put(25, new Consumer(“ramiz”,“pcs!@#”, new Tackle(“Bhavani peth”,“jalgaon”)));
for(last Entry<Integer, Consumer> consumer : customers.entrySet()){
out.println(consumer.getValue().getAddress());
}
}
}
|
Supply techzoo.org