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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With