-4

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 gradebetween 0 to 5. Then map the gradeto 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

sumu00
  • 49
  • 7

2 Answers2

5

Assigning a new value to the same key will override the old value, so if you have a maximum of 5 different keys (1-5) your map has a maximum size of 5.

You should use the name as the key, since they're unique. Then several students can have the same grade.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • @Kayaman, ah thanks, I understand what is going on now. The size is triggered by the value I get from `grade`. – sumu00 Mar 08 '18 at 12:05
  • @Pshemo, how do I get 0-5? Thanks. – sumu00 Mar 08 '18 at 12:06
  • @Pshemo err yeah, of course. – Kayaman Mar 08 '18 at 12:06
  • 1
    @sumu00 Lets start with what you have now: `(int)(Math.random()*5+1);`. `Math.random()` can only generate value from range `[0;1)` (or lets write it as `[0; 0.9999999...]`). When we multiply it `5*[0;1)` it gives us new range `[0; 4.9999999...]`. After adding `+1` range becomes `[1; 5.99999999]`. By casting to `(int)` we remove `.999...` part so range is `[1; 5]`. If you want to get `[0; 5]` you can create range `[0; 5.9999....]` before casting. To generate such range you need `6*[0; 0.99999...]`. So value from such range can be generated using `int value = (int)(6*Math.random())`. – Pshemo Mar 08 '18 at 12:16
  • @Pshemo, such a good answer! Thanks a lot! – sumu00 Mar 08 '18 at 13:22
3

You use the grades as keys

map.put(grade, name[i]);  

Since the range of grades is [1, 5], the map will not become larger than 5.

Pshemo
  • 122,468
  • 25
  • 185
  • 269