java - HashMap 的意外输出

标签 java collections

代码:

public class Puzzle23{
    void Puzzle23(){
        map1.put(String1, "1");
        map1.put(String2, "2");
    }

    private final NewMap map1 = new NewMap();
    private static final String String1 = new String("J2eeSig");
    private static final String String2 = new String("J2eeSig");

    public static void main(final String args[]){
        final Puzzle23 p22 = new Puzzle23();
        final Map<String, String> map2 = new HashMap();

        map2.put(String1, "1");
        map2.put(String2, "2");
        System.out.println(p22.map1.size() == map2.size() ? true : false);
        p22.map1.remove(new String(String1));
        map2.remove(new String(String2));
        System.out.println(p22.map1.size() == map2.size() ? true : false);
    }

    class NewMap extends IdentityHashMap<String, String>{
        public void put(final String... values){
            super.put(values[0], values[1]);
        }

        public int size(){
            return super.size() + 1 - 1 / 1 * 1;
        }
    }
}

实际结果:-

false
true

预期结果:-

true
true

为什么???

最佳答案

因为使用NewMapIdentityHashMap。检查说明的文档

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

编辑: 不管怎样,我在你的代码中发现了一个错误。 void Puzzle23() 不是构造函数,它是一种方法。必须在没有返回值的情况下定义构造函数(例如 Puzzle23())。所以你永远不会填写 map1。当您修复此问题时,您会意识到由于 IdentityHashMap,您的输出为 false false。当您将 map1 切换为 HashMap 时,输出将如您预期的那样为 true true。无论如何,请检查 IdentityHashMap 的文档。

关于java - HashMap 的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5323533/

相关文章:

java - ArrayList 线程安全测试代码失败

java - 使用 equals() 的给定实现检查特定对象是否在列表中

java - JPA 在表达式 : what is collection size limit? 中

java - Hibernate Spring JPA javax.persistence.TransactionRequiredException : No transactional EntityManager available

java - 作业的运行资格与 JobLauncherTestUtils 不起作用

java - 使用 Producer 方法时,CDI (Weld SE) 不会注入(inject)内部依赖项

java - 检查一个对象是否来自另一个(比如固定的)对象列表的最佳方法是什么?

java - 从 map 中消除负数并与其他正数求和的算法

java - 将 JPanel 添加到 JFrame : java. lang.IllegalArgumentException 的问题:无法添加到布局:约束必须是字符串(或 null)

java - 多线程环境下使用哪些Java集合类比较好