-4

I have written the program as follows. I want to sort the linked list on basis of the String a in the class player.

now the output is

nagpur rathi
akola ashwin

but after sorting with the variable a it should be

akola ashwin
nagpur rathi

The code is as follows:

package link.demo;

public class Player
{
    String a,b;

    Player()
    {
    }

    Player(String city,String name)
    {
        a=city;
        b=name;
    }
}

package link.demo;

import java.util.Iterator;
import java.util.LinkedList;

public class Linkdemo 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)throws Exception
    {
        // TODO code application logic here
        Player b=new Player("nagpur","rathi");
        Player c=new Player("akola","ashwin");
        //player temp=new player();
        LinkedList<Player> l= new LinkedList<Player>();

        l.add(b);
        l.add(c);

        Iterator<Player> itr=l.iterator(); 

       while(itr.hasNext())
       {
           Player temp=itr.next();
           System.out.println(temp.a+" "+temp.b);
       }
    }
}
4

1 回答 1

1

好吧,播放器(数据)类必须实现 Comparable。如http://docs.oracle.com/javase/6/docs/api/java/lang/Comparable.html中所述

该接口对实现它的每个类的对象进行了总排序。这种排序称为类的自然排序,类的 compareTo 方法称为其自然比较方法。

实现此接口的对象列表(和数组)可以由 Collections.sort(和 Arrays.sort)自动排序。

因此,在实现这一点后,您可以调用Collections.sort(l). 我建议阅读http://www.onjava.com/pub/a/onjava/2003/03/12/java_comp.html,它将教你基础知识。

于 2013-04-22T11:08:43.887 回答