Collections.sort()在AbstractList类上失败

时间:2014-11-17 19:24:33

标签: java class sorting

public class LinkedList extends AbstractList<Node2>
{
    Node2 n;
    int sizee;
    public LinkedList()
    {
        n=null;
        sizee=0;
    }
    @Override
    public Node2 get(int poz)
    {
        Node2 pp=this.n;
        for(int i=1;i<=poz;i++)
        {
            if(pp==null)
                break;
            pp=pp.nextNode;
        }
        return pp;
    }
    public Node2 set(int ind,Node2 x)
    {
        Node2 pp=this.n;
        Node2 t=n;
        for(int i=1;i<=ind;i++)
        {
            if(pp==null)
                break;
            t=pp;
            pp=pp.nextNode;
        }
        pp.cargo=x.cargo;
        return t;
    }
    public boolean add(Node2 x)
    {
        boolean found;
        Node2 r=x.clone();
        Node2 p;
        if(this.n==null)
        {
            n=r;
            sizee++;
            return true;
        }
        else
        {
            p=n;
            while(p.nextNode!=null)
            {
                p=p.nextNode;
            }
            p.nextNode=r;
            sizee++;
            return true;
        }
    }
    public int size()
    {
        return this.sizee;
    }
    public Iterator<Node2> iterator() {
        return new MyIterator2(this.n);
    }
    public String toString()
    {
        Node2 p=this.n;
        String str="";
        while(p!=null)
        {
            str+=p.cargo+" ";
            p=p.nextNode;
        }
        return str;
    }
}
class Node2 
{
    Object cargo;
    Node2 nextNode;
    public Node2(Object cargo)
    {
        this.cargo=cargo;
    }
    public Node2 clone()
    {
        Node2 k=new Node2(this.cargo);
        k.nextNode=this.nextNode;
        return k;
    }
}
class MyIterator2 implements Iterator<Node2>
{
    Node2 r;
    public MyIterator2(Node2 b)
    {
        this.r=b.clone();
    }
    public boolean hasNext()
    {
        if(r!=null)
        {
            return true;
        }
        return false;
    }
    public Node2 next()
    {
        Node2 u;
        u=r;
        r=r.nextNode;
        return u;
    }
}

我的比较器看起来像这样:

 static class C2 implements Comparator<Node2>
        {
            public int compare(Node2 s1,Node2 s2)
            {
                return ((s1.cargo).toString()).compareTo((s2.cargo).toString());
            }
        }

我的问题是,当我尝试使用Collections.sort对LinkedList对象进行排序时,列表中的一些元素会消失,而其他元素会重复。例如对于3 2 5 9 8排序后变为2 3 5 8 8.我猜是问题出在set()方法但不确定。它不会抛出任何异常,但结果是错误的。谢谢你提前!

0 个答案:

没有答案
相关问题