简介
java 核心编程
关于TreeSetTest的知识
输出
[[descrition=Toaster,partNumber=1234], [descrition=Widget,partNumber=4562], [descrition=Modem,partNumber=9912]]
[[descrition=Modem,partNumber=9912], [descrition=Toaster,partNumber=1234], [descrition=Widget,partNumber=4562]]
有两个输出,第一个是默认自带的比较函数结构
public int compareTo(Item other){
int diff = Integer.compare(partNumber, other.partNumber); // 先比较编号再比较字符串
return diff != 0? diff : description.compareTo(other.description);
}
表示 先比较编号再比较字符串
第二个输出,设定的比较方式采用字符串比较的方式进行排序。
NavigableSet
code
import java.util.*;
public class TreeSetTest {
public static void main(String[]args){
SortedSet<Item> parts = new TreeSet<>();
parts.add(new Item("Toaster", 1234));
parts.add(new Item("Widget", 4562));
parts.add(new Item("Modem", 9912));
System.out.println(parts);
NavigableSet<Item> sortByDescription = new TreeSet<>(Comparator.comparing(Item::getDescription)); // 设定的比较方式,直接通过字符串进行排序
sortByDescription.addAll(parts);
System.out.println(sortByDescription);
}
}
import java.util.*;
public class Item implements Comparable<Item>{
private String description;
private int partNumber;
/**
* Constructs an item.
*
* @param aDescription
* the item's description
* @param aPartNumber
* the item's part number
*/
public Item(String aDescription, int aPartNumber){
description = aDescription;
partNumber = aPartNumber;
}
public String getDescription(){
return description;
}
public String toString(){
return "[descrition=" + 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);
}
}