标签:object public double compare products
/* 让SortedSet集合做到排序还有另一种方式:java.util.Comparator; 单独编写一个比较器. */ import java.util.*; public class SortedSetTest03{ public static void main(String[] args){ //创建TreeSet集合的时候提供一个比较器. //SortedSet products = new TreeSet(new ProductComparator()); //匿名内部类:不推荐使用,因为比较器无法得到重复利用。 SortedSet products = new TreeSet(new Comparator(){ //需求:按照商品价格排序 public int compare(Object o1, Object o2){ double price1 = ((Product)o1).price; double price2 = ((Product)o2).price; if(price1==price2){ return 0; }else if(price1>price2){ return 1; }else{ return -1; } } }); Product p1 = new Product(3.4); Product p2 = new Product(4.0); Product p3 = new Product(3.0); Product p4 = new Product(2.0); Product p5 = new Product(5.0); //添加元素 products.add(p1); products.add(p2); products.add(p3); products.add(p4); products.add(p5); //遍历 Iterator it = products.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } } class Product{ double price; Product(double price){ this.price = price; } public String toString(){ return price + ""; } } //单独编写一个比较器 /* class ProductComparator implements Comparator{ //需求:按照商品价格排序 public int compare(Object o1, Object o2){ double price1 = ((Product)o1).price; double price2 = ((Product)o2).price; if(price1==price2){ return 0; }else if(price1>price2){ return 1; }else{ return -1; } } } */
本文出自 “gaogaozi” 博客,请务必保留此出处http://hangtiangazi.blog.51cto.com/8584103/1669871
标签:object public double compare products
原文地址:http://hangtiangazi.blog.51cto.com/8584103/1669871