Pergunta

I have a following program where I have a hashmap. The keys of the hashmap are simple integers and the values are integer arrays. The program is as follows:

Map<String , int []> myMap = new HashMap<String , int []>();

 myMap.put("EvenNumbers", new int[]{2,4,6,8,10,12,14,16,18,20});
 myMap.put("OddNumbers", new int[]{1,3,5,7,9,11,13,15,17,19});
 myMap.put("DivisibleByThree", new int[]{3,6,9,12,15,18});
 myMap.put("DivisibleByFive", new int[]{5,10,15,20});

 int[] array = new int[]{1,3,5,7,9,11,13,15,17,19};

 System.out.println(myMap.containsKey("EvenNumbers"));
 System.out.println(myMap.containsKey("OddNumbers"));

 //The following two lines produce a false output. Why ?         
 System.out.println(myMap.containsValue(new int[]{5,20,15,20} ));
 System.out.println(myMap.containsValue(array));

while the following code produces a true value

 HashMap newmap = new HashMap();

      // populate hash map
      newmap.put(1, "tutorials");
      newmap.put(2, "point");
      newmap.put(3, "is best"); 

      // check existence of value 'point'
      System.out.println("Check if value 'point' exists: " + 
      newmap.containsValue("point"));

Why is this so ? Where have I gone wrong? what is the caoncept that I am missing? I feel that I am doing the same thing in both the cases. I am new to the java environment , hence the confusion. Please help me clear the concepts.

Foi útil?

Solução 2

this is because boolean x = new int[]{ 5, 20, 15, 20 }.equals(new int[] { 5, 20, 15, 20 }); returns false. One solution is to use java.nio.IntWrapper, try this

    map.put("a1", IntBuffer.wrap(new int[]{ 5, 20, 15, 20 }));
    boolean equals = map.containsValue(IntBuffer.wrap(new int[]{ 5, 20, 15, 20 }));

Outras dicas

Take a look at equals vs Arrays.equals in Java

Map uses equals to determine, if a value is present in a Map, but it means different things:

  • When you compare 2 arrays in the first case, you are checking, if this is the same array meaning location in memory, not the content of an array.
  • In the second case, String.equals actually checks if this is the same String.

Because Map.containsValue() is looking for a match based on the .equals() method of the value type. The .equals() method of an int[] is effectively checking that the two references are the same.

You can check this for yourself by putting your array variable in the map and then asking the map if it contains your array variable. It should return true since it does contain an int[] with the same reference.

The reason it works for "point" is because "point".equals("point") returns true.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top