从头认识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<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接口,我们在compareTo方法里面已经做了去重和排序,假设仅仅是做当中一个。仅仅是实现一种功能。


总结:这一章节主要讨论了使用TreeSet须要注意的地方。


这一章节就到这里。谢谢。

-----------------------------------

文件夹



原文地址:https://www.cnblogs.com/wgwyanfs/p/6971698.html