TreeSet测试例

这里定义了两个版本:一个按照部件编号排序,所以对同名的会作为不同个体输出
下面是用定制的比较器按名输出,所以同名元素当做一个输出!如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);
		
	}
	
	
	
	
	
	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值