在标准Java库中,查找两个列表是否包含完全相同的元素的最简单方法是什么?
如果两个列表是相同的实例,则无关紧要,如果列表的类型参数不同则无关紧要.
例如
List list1
List<String> list2;
// ... construct etc
list1.add("A");
list2.add("A");
// the function, given these two lists, should return true
Run Code Online (Sandbox Code Playgroud)
我知道可能有些东西盯着我:-)
编辑:为了澄清,我正在按顺序寻找完全相同的元素和元素数量.
编辑:谢谢你指出我看不见的明显答案:-)
虽然到目前为止给出的所有答案都是正确的,但有些答案比其他答案更正确,所以在接受之前我会等待一段时间以获得最好的四舍五入的答案.
我学会了如何使用比较器,但我对比较器有困难.我的代码中有错误:
Exception in thread "main" java.lang.ClassCastException: New.People cannot be cast to java.lang.Comparable
at java.util.Arrays.mergeSort(Unknown Source)
at java.util.Arrays.sort(Unknown Source)
at java.util.Collections.sort(Unknown Source)
at New.TestPeople.main(TestPeople.java:18)
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
import java.util.Comparator;
public class People implements Comparator {
private int id;
private String info;
private double price;
public People(int newid, String newinfo, double newprice) {
setid(newid);
setinfo(newinfo);
setprice(newprice);
}
public int getid() {
return id;
}
public void setid(int id) {
this.id = id;
}
public String getinfo() {
return info;
}
public void setinfo(String info) …Run Code Online (Sandbox Code Playgroud) 如何检查两个ArrayLists是否彼此不同?我不在乎有什么不同,我只是想知道他们是不是一样.
我每分钟从数据库中获取分数列表,并且只有当我获取的分数列表与我在一分钟前获取的分数列表不同时,我才想将其发送给客户端.
现在,ArrayList的值实际上是我创建的一个类(包含name,lvl,rank,score).
我需要实施equals()吗?