要求使用
TreeSet
集合进行存储数据并遍历。
1.
定义一个手机类,包含手机品牌,价格,封装该类的属性,并定义该类的有参构造方法实现对属性的赋值
。
2
.创建5个手机类对象依次存放到TreeSet中。
3.自定义一个比较器(按照价格降序排列),将1中的集合元素按照比较器的顺序进行存放。
4.使用迭代输出该集合类中的所有元素。
![](https://img-blog.csdnimg.cn/direct/b38cd9c876364d04b6cc65035088fea5.png)
package eight.set.lianxi; public class Phone { private String brand; private int price; public Phone(String brand, int price) { this.brand = brand; this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { return "Phone{" + "brand='" + brand + '\'' + ", price=" + price + '}'; } }
package eight.set.lianxi; import java.util.Comparator; public class MyComparator implements Comparator<Phone> { @Override public int compare(Phone o1, Phone o2) { return o2.getPrice()- o1.getPrice(); } }
package eight.set.lianxi; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; public class PhoneTest { public static void main(String[] args) { Phone p1 = new Phone("苹果",5800); Phone p2 = new Phone("三星",3899); Phone p3 = new Phone("华为",6999); Phone p4 = new Phone("小米",2500); Phone p5 = new Phone("oppo",3600); TreeSet<Phone> ts = new TreeSet<>(new MyComparator()); ts.add(p1); ts.add(p2); ts.add(p3); ts.add(p4); ts.add(p5); Iterator<Phone> it = ts.iterator(); while(it.hasNext()){ Phone n = it.next(); System.out.println(n); } } }