I am trying to understand how Map interface works in Java. What I am trying to do is: run through the array of strings and for each name in the array name[]
put a random grade
between 0 to 5. Then map the grade
to name[i]
. However, the map size gets weird, although I have 10 elements in array, the map.size()
is 5 after mapping. Why does the program count the same size several times (see output)? Here is the code and output below:
import java.util.*;
class MapInterfaceExample{
public static void main(String[] args){
int grade = 0;
String[] name = {"Lisa", "Dan", "John", "Adam", "George", "Amanda", "Sarah", "James", "Derek", "Sam"};
Map<Integer,String> map=new HashMap<Integer,String>();
for(int i=0; i<name.length; i++){
grade = (int)(Math.random()*5+1);
map.put(grade, name[i]);
//System.out.println(grade + "\t"+ name[i]);
System.out.println("Size of map "+ map.size());}
}
}
Output:
Size of map 1
Size of map 2
Size of map 2
Size of map 2
Size of map 2
Size of map 3
Size of map 3
Size of map 4
Size of map 4
Size of map 5