如何在java中使用对象对链表进行排序
我用Java创建了一个带有对象的链表(通用容器)。我需要重新编写insert方法,使列表按键的字母顺序排序。这是我目前的代码: 容器:如何在java中使用对象对链表进行排序,java,list,sorting,linked-list,compareto,Java,List,Sorting,Linked List,Compareto,我用Java创建了一个带有对象的链表(通用容器)。我需要重新编写insert方法,使列表按键的字母顺序排序。这是我目前的代码: 容器: class Sellbeholder<N extends Comparable<N>, V> implements INF1010samling<N,V> { private Keeper første; private int ant = 0; private class Keeper { Keeper nest
class Sellbeholder<N extends Comparable<N>, V> implements INF1010samling<N,V> {
private Keeper første;
private int ant = 0;
private class Keeper {
Keeper neste;
N n;
V v;
Keeper(N n,V v) {
this.n = n;
this.v = v;
}
}
这是Person对象,我将其放入容器(链表):
这就是我如何创造人并把他们放在容器中:
Sellbeholder <String,Person> b1 = new Sellbeholder <String,Person>();
Person a = new Person("William");
b1.PutIn("William",a);
尝试使用或迭代列表,直到找到正确的位置:
public void PutIn(N n, V v) {
Keeper kep = new Keeper(n,v);
// you will insert between previous and current
Keeper previous = null;
Keeper current = første;
// loop until you get the right place
while (current != null && ((current.n).compareTo(n) > 0)) {
previous = current;
current = current.neste;
}
// insert your stuff there (if there were no previous, then this is the first one)
if (previous == null) {
første = kep;
} else {
previous.neste = kep;
}
// Set the next Keeper
kep.neste = current;
ant++;
}
这将使您的列表保持有序。您有什么理由不能使用树集来代替?如果需要链表,可以使用java.util.LinkedList;如果需要按键排序的映射,可以使用java.util.TreeMap。我认为TreeMap可以满足您的要求。@anoopelias可能他必须自己实现它,例如像做作业一样。我建议使用Java约定,以小写字母开始方法,并避免使用国家语言字符。这正是我所寻求的。非常感谢你!
Sellbeholder <String,Person> b1 = new Sellbeholder <String,Person>();
Person a = new Person("William");
b1.PutIn("William",a);
for(Keeper nn = første; nn!= null; nn = nn.neste) {
if(nn.n.compareTo(kep.n) > 0) {
//Do something here
public void PutIn(N n, V v) {
Keeper kep = new Keeper(n,v);
// you will insert between previous and current
Keeper previous = null;
Keeper current = første;
// loop until you get the right place
while (current != null && ((current.n).compareTo(n) > 0)) {
previous = current;
current = current.neste;
}
// insert your stuff there (if there were no previous, then this is the first one)
if (previous == null) {
første = kep;
} else {
previous.neste = kep;
}
// Set the next Keeper
kep.neste = current;
ant++;
}