繁体   English   中英

如何使用java中的对象对链表进行排序

[英]How to sort a linked list with objects in java

我用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 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

在列表中迭代,直到找到合适的位置:

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

这将保持您的清单订购。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM