有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HashSet clone()方法

我使用clone()创建了现有哈希集的克隆,然后比较了它们的引用,如下所示:

HashSet<Employee> h = new HashSet<>();
HashSet<Employee> h1=(HashSet<Employee>) h.clone();
System.out.println(h==h1);

输出:

false

既然我们在创造肤浅的复制品,这难道不是真的吗


共 (2) 个答案

  1. # 1 楼答案

    在java==for objects中,检查对象是否是完全相同的对象

    如果你去检查克隆方法:

    public Object clone() {
        try {
            HashSet<E> newSet = (HashSet<E>) super.clone();
            newSet.map = (HashMap<E, Object>) map.clone();
            return newSet;
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }
    

    很容易看出它正在创建一个新对象。所以现在你有两个不同的物体,它们大致相等

  2. # 2 楼答案

    ^{} overrides^{}方法^{} class

    The general intent is that, for any object x, the expression:  
      x.clone() != x
    
    will be true, and that the expression:
      x.clone().getClass() == x.getClass()
    
    will be true, but these are not absolute requirements. While it is typically the case that:
      x.clone().equals(x)
    will be true, this is not an absolute requirement.
    

    按照惯例,此方法返回的对象应独立于此对象(正在克隆)

    在Java中,==检查引用而不是对象,所以h==h1在您的例子中是false