为什么HashSet<Integer>存储的是整数值本身,而HashSet<Demo>存储的是Demo对象的引用?

Why does HashSet<Integer> store the integer value itself, but HashSet<Demo> stores the reference of the Demo object?

大家好,

class Demo{
    private int a;
    Demo(int a){
        this.a = a;
    }
}

public class Test{
    public static void main(String[] args){
        
        Demo d1 = new Demo(10);
        Demo d2 = new Demo(20);
        
        Set<Demo> set = new HashSet<Demo>();
        
        set.add(d1);
        set.add(d2);
        
        System.out.println(set);
    }
}

输出:[javaSE_8.Demo@15db9742,javaSE_8.Demo@6d06d69c]

我明白上面的代码是打印对象引用。

public class Test{
    public static void main(String[] args){
        
        Integer i1 = 10;
        Integer i2 = 20;
        
        Set<Integer> set = new HashSet<Integer>();
        
        set.add(i1);
        set.add(i2);
        
        System.out.println(set);
    }
}

输出:[20, 10]

尽管 Integer 是一个 class(Wrapper class) 并且 i1、i2 是它的对象,但此代码打印值本身。

我想知道为什么会这样,或者为什么会存在这种差异。

谢谢, 苏珊

HashSet<Demo>HashSet<Integer> 都存储对对象的引用。

System.out.println(set) 打印由 set.toString() 方法编辑的 String return。此方法为集合中的每个 object 调用 object.toString(),并将它们与 space.

连接起来

现在因为 Integer.toString() return 是 String 的实际值,您看到的是 Integer 的打印值,而 [=20] =], Demo.toString() returns 作为 String 的对象引用,因为它是默认方法 java.lang.Object.toString()。您可以将 Demo 中的此方法重写为 return 实际值作为 String.