有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java比较两个列表

我想比较两个列表。因为我们使用List编写接口代码,它不会从对象类继承equals。我该怎么做


共 (3) 个答案

  1. # 1 楼答案

    您仍然可以使用equals。所有对象都实现了它,您的列表仍然是对象,并根据需要覆盖equals

  2. # 2 楼答案

    这是一个常见的故事:你必须考虑“浅等于”和“深等于”。p>

    从java中获得的默认行为。对象是“浅相等”。它将检查列表1和列表2是否是相同的引用:

    List list1 = new ArrayList();
    List list2 = list1;
    
    list1.equals(list2); // returns true;
    

    如果您想要“deepequals”,请实例化扩展AbstractList的任何内容,例如ArrayList

    List<String> list1 = new ArrayList<>();
    List<String> list2 = new ArrayList<>();
    
    list1.add("hello");
    list2.add("hello");
    System.out.println(list1.equals(list2)); // will print true
    
    list1.add("foo");
    list2.add("bar");
    System.out.println(list1.equals(list2)); // will print false
    
  3. # 3 楼答案

    即使List接口不包含equals方法,列表类也可以(并且确实)实现equals方法

    API docs on ^{}(例如ArrayListLinkedListVector继承):

    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.

    例如toStringhashCode方法等也是如此


    正如@Pascal在注释中提到的,List接口提到了equals方法,并在文档中说明了以下内容:

    The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods.