我有一个Gift类型的arrayList 每个Present对象都有字段String name,String type,double Cost
我想找到一种方法,使用每个当前的成本
对arrayList进行排序我使用的语言是Java
请如何做到这一点
答案 0 :(得分:1)
我想找到一种方法,使用每个当前的成本
对arrayList进行排序
您需要:
Comparable
Comparator
以下是我展示这两种方法的示例:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
return p1.getAge() - p2.getAge();
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
答案 1 :(得分:0)
您是否看过类似的界面? http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html?
请查看以下问题,了解如何实现此face. https://stackoverflow.com/questions/3718383/java-class-implements-comparable
答案 2 :(得分:0)
您可以使用Comparable or Comparator。在您的情况下,可比性更好。