这里定义了两个版本:一个按照部件编号排序,所以对同名的会作为不同个体输出
下面是用定制的比较器按名输出,所以同名元素当做一个输出!如Faker改为Master,输出·元素个数分别为4,3
package 集合;
import java.util.*;
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Item> parts = new TreeSet<Item>();
parts.add(new Item("Toaster",1234));
parts.add(new Item("Widget",4562));
parts.add(new Item("faker",9912));
parts.add(new Item("Moster",2365));
System.out.println(parts);
TreeSet<Item> sortByDescription = new TreeSet<Item>(Comparator.comparing(Item::getDescription));
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
package 集合;
import java.util.*;
public class Item implements Comparable<Item>
{
private String description;
private int partNumber;
public Item(String aDescription,int aPartNumber)
{
description = aDescription;
partNumber = aPartNumber;
}
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 Objects.equals(description,other.description)&&partNumber==other.partNumber;
}
public int hashCode() {
return Objects.hash(description,partNumber);
}
public int compareTo(Item other)
{
int diff = Integer.compare(partNumber,other.partNumber);
return diff !=0 ?diff:description.compareTo(other.description);
}
}