3

Javaでオブジェクトを使用してリンクリスト(ジェネリックコンテナ)を作成しました。リストをキーのアルファベット順にソートするには、insert-methodを書き直す必要があります。これはこれまでの私のコードです:

容器:

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

これは私がコンテナ(リンクリスト)に入れているPerson-objectです:

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-metohodを使用してオブジェクトを配置する場所を確認する必要があることはわかっていますが、リンクリストの構造をどのように設定する必要があるかわかりません。私はこれから始めました:

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(リストl)またはCollections.sort(リストl、コンパレータc)を使用してみてください

于 2013-02-27T15:31:03.977 に答える