Search code examples
javacollectionsclone

HashSet clone() method


I have created a clone of the existing HashSet using clone() and then comparing their references like below:

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

OUTPUT:

false

Shouldn't this be true since we are creating shallow copies?


Solution

  • HashSet overrides the clone() method of Object 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.
    

    By convention, the object returned by this method should be independent of this object (which is being cloned).

    In Java, == checks for references not objects so, h==h1 is false in your case.