3

我用 Java 中的对象创建了一个链表(通用容器)。我需要重新编写我的插入方法以使列表按字母顺序按键排序。到目前为止,这是我的代码:

容器:

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

这是我的插入方法(我需要重写):

public void PutIn(N n, V v) {
    Keeper kep = new Keeper(n,v);
    kep.neste = første;
    første = kep;
    ant++;

这是我放入容器(链表)中的人员对象:

class Person {

    String name;

    Person(String n) {
        this.name = n;
    }
}

这就是我创建人员并将它们放入容器中的方式:

Sellbeholder <String,Person> b1 = new Sellbeholder <String,Person>();
Person a = new Person("William");
b1.PutIn("William",a);

任何帮助我都会非常感激。我知道我需要使用 CompareTo-method 来检查对象的放置位置,但我不确定应该如何设置链表的结构。我已经开始这样做了:

for(Keeper nn = første; nn!= null; nn = nn.neste) {

    if(nn.n.compareTo(kep.n) > 0) {
        //Do something here
4

2 回答 2

1

迭代列表,直到找到正确的位置:

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++;
}

这将使您的列表保持有序。

于 2013-02-27T15:39:48.787 回答
0

尝试使用Collections.sort(List l)Collections.sort(List l, Comparator c)

于 2013-02-27T15:31:03.977 回答