從頭認識java-15.4 使用TreeSet需要注意的地方
接著上一章節,我們繼續來討論使用TreeSet需要注意的地方。
2.TreeSet
特點:
(1)元素是有序的
(2)元素是重複的,需要去重
(3)必須實現Comparable介面
(4)底層的資料存放區是按照樹的結構來儲存的
我們修改一下上一章節的代碼:
package com.ray.ch15;import java.lang.reflect.InvocationTargetException;import java.util.Set;import java.util.TreeSet;public class Test {public static Set fill(Set set, Class type)throws InstantiationException, IllegalAccessException,IllegalArgumentException, SecurityException,InvocationTargetException, NoSuchMethodException {for (int i = 0; i < 10; i++) {set.add(type.getConstructor(int.class).newInstance(i));}return set;}public static void test(Set set, Class type)throws IllegalArgumentException, SecurityException,InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {fill(set, type);fill(set, type);fill(set, type);System.out.println(set);}public static void main(String[] args) throws IllegalArgumentException,SecurityException, InstantiationException, IllegalAccessException,InvocationTargetException, NoSuchMethodException {test(new TreeSet(), TreeType.class);// test(new TreeSet(), SetType.class);//// java.lang.ClassCastException// test(new TreeSet(), HashType.class);//// java.lang.ClassCastException}}class SetType {private int id = 0;public int getId() {return id;}public void setId(int id) {this.id = id;}public SetType(int i) {id = i;}@Overridepublic String toString() {return id + "";}@Overridepublic boolean equals(Object obj) {return obj instanceof SetType && (id == ((SetType) obj).id);}}class HashType extends SetType {public HashType(int i) {super(i);}@Overridepublic int hashCode() {return getId();}}class TreeType extends HashType implements Comparable {public TreeType(int i) {super(i);}@Overridepublic int compareTo(TreeType o) {if (o.getId() > getId()) {// 排序return -1;} else {if (o.getId() == getId()) {// 去重return 0;} else {return 1;}}}}
輸出:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
解釋一下上面的代碼:
(1)fill方法:通過泛型和反射,往傳進來的set裡面添加資料
(2)test方法:我們通過多次的往set裡面填充資料,看看set是否去重
(3)SetType:原始類型,只是簡單實現了equals方法和toString方法,toString這裡通過輸出id來表示對象
(4)HashType:繼承SetType,再實現了hashCode方法拋異常
(5)TreeType:實現Comparable介面,我們在compareTo方法裡面已經做了去重和排序,如果只是做其中一個,只是實現一種功能。
總結:這一章節主要討論了使用TreeSet需要注意的地方。
這一章節就到這裡,謝謝。