Java 核心技术(第八版)卷1:基础知识:例13-3P576TreeSetTest

superfreak 2022-05-14 15:06:53 阅读数:704

java技术核心技术核心第八版

//本程序创建了两个item 对象的树集,

// 第一个按照部件编号排序,这是item对象的默认排序顺序,
// 第二个使用一个定制的比较器来按照描述信息排序 

import java.util.*;
//本程序创建了两个item 对象的树集,第一个按照部件编号排序,这是item对象的默认排序顺序,
// 第二个使用一个定制的比较器来按照描述信息排序
public class TreeSetTest {
public static void main(String[] args)
{
SortedSet<Item> parts=new TreeSet<Item>();
parts.add(new Item("Toaster",1234));
parts.add(new Item("Widget",1162));
parts.add(new Item("Modem",9912));
System.out.println("sort by partNumber :"+parts);
SortedSet<Item> sortByDescription=new TreeSet<Item>(new Comparator<Item>() {
@Override
public int compare(Item a, Item b) {
String descrA=a.getDescription();
String descrB=b.getDescription();
return descrA.compareTo(descrB);
}
});
sortByDescription.addAll(parts);
System.out.println("sort by Description:"+sortByDescription);
}
}
//An item with a description and a part number
class Item implements Comparable<Item>
{
//构建一个 item
public Item(String aDescription,int aPartNumber)
{
description=aDescription;
partNumber=aPartNumber;
}
//get description of the item
public String getDescription()
{
return description;
}
public String toString()
{
return "description="+description+",partNumber="+partNumber+"]";
}
public boolean equals(Object otherObject)
{
if(this==otherObject)return true;
if(otherObject==null)return false;
if(getClass()!=otherObject.getClass())return false;
Item other=(Item)otherObject;
return description.equals(other.description)&&partNumber==other.partNumber;
}
public int hashCode()
{
return 13*description.hashCode()+17*partNumber;
}
public int compareTo(Item other)
{
return partNumber-other.partNumber;
}
private String description;
private int partNumber;
}

运行结果:

sort by partNumber :[description=Widget,partNumber=1162], description=Toaster,partNumber=1234], description=Modem,partNumber=9912]]
sort by Description:[description=Modem,partNumber=9912], description=Toaster,partNumber=1234], description=Widget,partNumber=1162]]

版权声明:本文为[superfreak]所创,转载请带上原文链接,感谢。 https://blog.csdn.net/superfreak/article/details/124765116