Java 集合 之 Collections
http://www.verejava.com/?id=17159773304835
// 对商家的产品(产品名称,产品价格)信息按价格排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// 对商家的产品(产品名称,产品价格)信息按价格排序
List list=new ArrayList();
list.add(new Product("华硕电脑", 4000));
list.add(new Product("东芝电脑", 3500));
list.add(new Product("联想电脑", 5000));
for(int i=0;i<list.size();i++)
{
Product p=(Product)list.get(i);
System.out.println(p.getName()+","+p.getPrice());
}
//Collections Arrays.sort()
Collections.sort(list,new DecendComparator());
System.out.println("排序完以后的结果:");
for(int i=0;i<list.size();i++)
{
Product p=(Product)list.get(i);
System.out.println(p.getName()+","+p.getPrice());
}
}
}
//产品类
public class Product implements Comparable{
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public int compareTo(Object o) {
Product p=(Product)o;
if(this.price<p.getPrice())
{
return 1;
}else if(this.price>p.getPrice())
{
return -1;
}
return 0;
}
}
//升序
import java.util.Comparator;
public class AscendComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Product p1=(Product)o1;
Product p2=(Product)o2;
if(p1.getPrice()<p2.getPrice())
{
return -1;
}else if(p1.getPrice()>p2.getPrice())
{
return 1;
}
return 0;
}
}
//降序
import java.util.Comparator;
public class DecendComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
Product p1=(Product)o1;
Product p2=(Product)o2;
if(p1.getPrice()<p2.getPrice())
{
return 1;
}else if(p1.getPrice()>p2.getPrice())
{
return -1;
}
return 0;
}
}