Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List , Vector comparison

I saw the following program on the internet

public class Test1{
 public static void main(String[] args)
 {
 Integer int1 = new Integer(10);
 Vector vec1 = new Vector();
 LinkedList list = new LinkedList();
 vec1.add(int1);
 list.add(int1);
 if(vec1.equals(list)) System.out.println("equal");
 else  System.out.println("not equal");
  }

}

The answer it print is "equal".

How it is possible?

Thanks

Dilip

like image 403
Dilip Ganesh Avatar asked Dec 09 '22 06:12

Dilip Ganesh


2 Answers

Because both a LinkedList and Vector implement List#equals()

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. This definition ensures that the equals method works properly across different implementations of the List interface.

Specifically, here is the exact reason for this behavior.

This definition ensures that the equals method works properly across different implementations of the List interface.

like image 84
Kal Avatar answered Dec 15 '22 00:12

Kal


Here's the API doc for Vector.equals() (other List implementations behave similarly):

Compares the specified Object with this Vector 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.

like image 28
Michael Borgwardt Avatar answered Dec 15 '22 00:12

Michael Borgwardt