Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java clone() and equals() check

For the following class, I understand that c1.equals(c3) returns false as c1.clone() creates a different reference that points to the same object. But why carList1.equals(carList2) returns true? why is it different from c1.equals(c3)? Many thanks in advance!

class Car implements Cloneable {
   private String plate;   
   private double maxSpeed;     
  public Car(String lp, double max) {
      license = lp;
      maxSpeed = max;
   }
  public static void main(String[] args) throws Exception{
      Car c1 = new Car("ABC123", 150.0);
      Car c2 = new Car("ABC123", 150.0);
      Car c3 = (Car) c1.clone();
      ArrayList<Car> carList1 = new ArrayList<Car>();
      carList1.add(c1);
      carList1.add(c2);
      ArrayList carList2 = (ArrayList) carList1.clone();
  } 
}
like image 411
user3735871 Avatar asked Sep 12 '14 10:09

user3735871


1 Answers

clone of ArrayList performs a shallow copy, i.e., it doesn't clone the elements contained within the ArratList, it just copies the references. That's why equals returns true, since it doesn't compare the references of the ArrayList objects, it compares the elements in the list.

public Object clone()

Returns a shallow copy of this ArrayList instance. (The elements themselves are not copied.)

public boolean equals(Object o)

Compares the specified object with this list for equality. Returns true if and only if the specified object is also a list, both lists have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).) In other words, two lists are defined to be equal if they contain the same elements in the same order.

On the other hand, Car, assuming you don't override its equals method to just compare the members, uses the default implementation of Object::equals, which compares object reference, and therefore a cloned Car is not equal to the original.

like image 132
Eran Avatar answered Nov 02 '22 07:11

Eran