2011-09-15 57 views
4

我在网上看到Java列表,向量比较

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"); 
    } 

}

答案它打印 “等于” 在下面的程序。

怎么可能?

感谢

迪利普

+0

http://www.java2s.com/Tutorial/Java/0140__Collections/Theequalsmethodisusedtocheckforelementequality.htm –

回答

8

因为无论一个LinkedList和Vector实施List#equals()

返回true当且仅当指定的对象也是一个列表,两个 列表具有相同的大小,并在 两个元素的所有相应对列表是平等的。 (如果 (e1 == null?e2 == null:e1.equals(e2)),则两个元素e1和e2相等。)换句话说,两个列表是 ,如果它们包含相同元素相同 的顺序。此定义确保equals方法在List接口的不同实现之间正常工作 。

具体而言,这是此行为的确切原因。

该定义确保equals方法在List接口的不同实现之间正常工作。

2

查看java.util.Vector中的平等的Javadoc:

/** 
    * 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 <em>equal</em>. (Two elements {@code e1} and 
    * {@code e2} are <em>equal</em> if {@code (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. 
    * 
    * @param o the Object to be compared for equality with this Vector 
    * @return true if the specified Object is equal to this Vector 
    */ 

equals方法是检查列表在同一顺序相同的内容。

4

下面是Vector.equals()的API文档(其他List实现的行为类似):

比较指定对象与此向量的相等。返回 当且仅当指定的Object也是List时,两个列表 的大小相同,并且两个列表中的所有对应元素对都相等。

+0

非常感谢您的回复 –

0
定义的

http://download.oracle.com/javase/1.4.2/docs/api/java/util/Vector.html#equals%28java.lang.Object%29

equals实现对Vector

比较指定对象与此向量的相等。当且仅当指定的对象也是一个List时,才返回true,两个列表具有相同的大小,并且两个列表中的所有相应元素对都相等。 (如果(e1 == null?e2 == null:e1.equals(e2)),两个元素e1和e2是相等的。)换句话说,如果两个列表包含相同元素的顺序相同。

两个VectorLinkedListAbstractList后代(在LinkedList的情况下,还有介于两者之间,我相信一个额外的类)。 AbstractList对象可以相互比较。

0

这是因为它们都是列表。

VectorLinkedList最终都从AbstractList继承。

请参阅the source code第512行的equals的实施。