对类ArrayList进行排序

时间:2015-05-10 00:57:50

标签: java sorting arraylist

我有一个ArrayList,它是我所调用的类的列表" Profile"。此配置文件包含一个名为"令牌"的整数。我如何生成这个arraylist的实例,但是它通过哪个配置文件具有最多的Tokens来组织它们?

这是我的个人资料类

public class Profile 
{
    private String name;
    private int tokens;

    public String getName() { return this.name; }
    public int getTokens() { return this.tokens; }
}

我将所有配置文件存储在ArrayList中,例如...

public static List<Profile> PROFILES = new ArrayList<Profile>();

任何帮助都将非常感激。

2 个答案:

答案 0 :(得分:0)

您的班级Profile必须实施Comparable界面并覆盖其compareTo方法,您可以在其中比较令牌&#39;价值,像这样:

public class Profile implements Comparable<Profile>
{
    @Override
    public int compareTo(Profile p) {
        return p.tokens < this.tokens;
    }
}

修改

    public class Profile implements Comparable<Profile>
    {
        @Override
        public int compareTo(Profile p) {
             if (p.tokens > this.tokens) { 
                 return -1; 
             } else if (p.tokens < this.tokens) { 
                 return 1; 
             } else 
                 return 0;
        }
    }

之后,您可以致电Collections.sort(PROFILES);

请注意,建议不要使用大写字母来编写变量。仅仅Profiles

会更好

答案 1 :(得分:-1)

class Dog implements Comparator<Dog>, Comparable<Dog>{
   private String name;
   private int age;
   Dog(){
   }
   Dog(String n, int a){
      name = n;
      age = a;
   }
   public String getDogName(){
      return name;
   }
   public int getDogAge(){
      return age;
   }
   // Overriding the compareTo method
   public int compareTo(Dog d){
      return (this.name).compareTo(d.name);
   }
   // Overriding the compare method to sort the age 
   public int compare(Dog d, Dog d1){
      return d.age - d1.age;
   }
}

public class Example{

   public static void main(String args[]){
      // Takes a list o Dog objects
      List<Dog> list = new ArrayList<Dog>();

      list.add(new Dog("Shaggy",3));
      list.add(new Dog("Lacy",2));
      list.add(new Dog("Roger",10));
      list.add(new Dog("Tommy",4));
      list.add(new Dog("Tammy",1));
      Collections.sort(list);// Sorts the array list

      for(Dog a: list)//printing the sorted list of names
         System.out.print(a.getDogName() + ", ");

      // Sorts the array list using comparator
      Collections.sort(list, new Dog());
      System.out.println(" ");
      for(Dog a: list)//printing the sorted list of ages
         System.out.print(a.getDogName() +"  : "+
         a.getDogAge() + ", ");
   }
}

This would produce the following result:
Lacy, Roger, Shaggy, Tammy, Tommy,
Tammy  : 1, Lacy  : 2, Shaggy  : 3, Tommy  : 4, Roger  : 10,