我有两个 ArrayList:一个字符串列表和一个整数列表。例如:
Bob 2
Kevin 6
Lane 4
Susan 2
//the ArrayLists will have more elements
我正在尝试对整数 ArrayList 进行排序(使用 MergeSort)并使 String ArrayList 对应于整数 ArrayList,例如:
Susan 2
Bob 2
Lane 4
Kevin 6
我想到的其他答案建议使用 Map(int 是键,String 是值);但是,我不能这样做,因为会有重复的键。
我读过 Guava 的 Multimap;但是,我不太愿意将 jar 文件包含到类路径中。
还有其他方法吗?
最佳答案
只要字符串和整数之间确实存在某种有意义的联系,最好的方法就是创建一个 Java 类来满足您的目的,例如:
public class MyClass implements Comparable<MyClass> {
private String myString;
private int myInt;
public MyClass(String s, int x) {
myString = s;
myInt = x;
}
public int getInt() {
return myInt;
}
public String getString() {
return myString;
}
public void setInt(int x) {
myInt = x;
}
public void setString(String s) {
myString = s;
}
// this method is the only method defined in the Comparable<T> interface
// and is what allows you to later do something like Collections.sort(myList)
public int compareTo(MyClass other) {
return myInt - other.getInt();
}
}
然后创建一个列表List<MyClass> ls = new ArrayList<MyClass>();
您可以将新创建的类的实例添加到其中。
这个类实现 Comparable 接口(interface)的事实意味着您可以使用 Java 的预定义排序方法,如 Collections.sort(),并让 Collections 类知道您希望如何对对象进行排序。相反,如果您更愿意实现自己的排序算法,则无需实现此接口(interface),但仍然是一种很好的做法。
关于java - Java中如何对应不同ArrayList中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578523/