Java: TreeSet

树集是一个有序集合,在对集合进行遍历时,每个值自动排序后呈现

排序使用的结构是红黑树,添加元素时都被放置在正确的排序位置上
若树包含n个元素,查找新元素正确位置平均需要logn次比较

要使用树集,必须要能够比较元素,元素必须实现Comparable接口,或构造集时提供一个Comparator

public class Test
{
	public static void main(String[] args) 
	{		
		//构造集时提供Comparator
		NavigableSet<Item> sortByDescription = new TreeSet<>(
			Comparator.comparing(Item::getDescription));
			
		sortByDescription.add(new Item("A", 1234));
		sortByDescription.add(new Item("B", 5678));
		System.out.println(sortByDescription);
	}
}

猜你喜欢

转载自blog.csdn.net/baidu_25104885/article/details/87923019
今日推荐