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;
}
利用TreeSet进行排序操作
最新推荐文章于 2024-08-14 22:53:03 发布