Я первоначально предположил, что это может быть связано с хэшмапом не сохранением порядка внедрения. But when I perform the same comparison with two LinkedHashMap objects, where the insertion order is indeed preserved, the equals() method still returns false.
Can someone explain why the equals() method returns false in both cases, even though:
- The content of the values is the same ([1, 2]),
- Порядок значений сохраняется в случае LinkedHashmap ?
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// HashMap example
Map map1 = new HashMap();
map1.put("a", 1);
map1.put("b", 2);
Map map2 = new HashMap();
map2.put("x", 1);
map2.put("y", 2);
System.out.println("map1 values: " + map1.values()); // prints [1, 2]
System.out.println("map2 values: " + map2.values()); // prints [1, 2]
System.out.println("map1.values().equals(map2.values()): " + map1.values().equals(map2.values())); // returns false
// LinkedHashMap example
Map map1l = new LinkedHashMap();
map1l.put("a", 1);
map1l.put("b", 2);
Map map2l = new LinkedHashMap();
map2l.put("x", 1);
map2l.put("y", 2);
System.out.println("map1l values: " + map1l.values()); // prints [1, 2]
System.out.println("map2l values: " + map2l.values()); // prints [1, 2]
System.out.println("map1l.values().equals(map2l.values()): " + map1l.values().equals(map2l.values())); // still returns false
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... -insertion
Мобильная версия