Java-15.4 TreeSetの使用に注意すべき点を最初から認識する

2826 ワード

次の章では、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<T> {
	public static <T> Set<T> fill(Set<T> set, Class<T> 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 <T> void test(Set<T> set, Class<T> 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>(), TreeType.class);
		// test(new TreeSet<SetType>(), SetType.class);//
		// java.lang.ClassCastException
		// test(new TreeSet<HashType>(), 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;
	}

	@Override
	public String toString() {
		return id + "";
	}

	@Override
	public boolean equals(Object obj) {
		return obj instanceof SetType && (id == ((SetType) obj).id);
	}
}

class HashType extends SetType {

	public HashType(int i) {
		super(i);
	}

	@Override
	public int hashCode() {
		return getId();
	}
}

class TreeType extends HashType implements Comparable<TreeType> {
	public TreeType(int i) {
		super(i);
	}

	@Override
	public 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インタフェースを実装し,comparareToメソッドでは既に脱重とソートを行い,そのうちの1つだけを行うと,1つの機能を実現する.
まとめ:この章では主にTreeSetの使用に注意すべき点について議論した.
この章はここまでです.ありがとうございます.
-----------------------------------
目次