利用TreeSet进行排序操作

package list;

import java.util.*;

public class TreeSetTest {
	public static void main(String[] args) {
		//按照默认的的排序-partNumber
		SortedSet<Item> parts = new TreeSet<Item>();
		parts.add(new Item("hello", 1234));
		parts.add(new Item("world", 2234));
		parts.add(new Item("hw", 3234));
		System.out.println(parts);
		
		//按照指定的进行排序-description
		SortedSet<Item> sortByDescription = new TreeSet<Item>(new Comparator<Item>() {
			@Override
			public int compare(Item a, Item b) {
				String desA = a.getDescription();
				String desB = b.getDescription();
				return desA.compareTo(desB);
			}
		});
		sortByDescription.addAll(parts);
		System.out.println(sortByDescription);
	}
}

class Item implements Comparable<Item> {
	
	public Item(String aDescription, int aPartNumber) {
		description = aDescription;
		partNumber = aPartNumber;
	}
	
	public String getDescription() {
		return description;
	}
	
	public String toString() {
		return "[description=" + description + ", partNumber=" + partNumber + "]";
	}
	
	@Override
	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.getDescription()) && partNumber == other.partNumber;
	}
	
	public int hashCode() {
		return 13*description.hashCode() + 17*partNumber;
	}
	
	@Override
	public int compareTo(Item other) {
		return partNumber - other.partNumber;
	}
	
	private String description;
	private int partNumber;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值