从头认识java-15.3 使用HashSet需要注意的地方

这一章节我们来讨论一下使用Set的各种实现需要注意的地方。

Set接口的常用实现类有:HashSet,TreeSet,LinkedHashSet


1.HashSet

大家对于HashSet的印象都是它可以去除重复的元素,每一个元素都是唯一的,但是这里面有一个前提,就是必须重写equals和hashcode方法。

大家的印象大都是下面这个:

package com.ray.ch15;

import java.util.HashSet;

public class Test {
	public static void main(String[] args) {
		HashSet<Integer> set = new HashSet<Integer>();
		set.add(1);
		set.add(2);
		set.add(3);
		for (int i = 0; i < 10; i++) {
			set.add(i);
		}
		System.out.println(set);
	}
}
输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

其实其中的原因是,set里面的equals和hashcode方法都继承了Object里面的,而Object里面的这两个方法刚好可以比较容易的对比java的基础类型,甚至java里面大部分的类型,因为大部分类型都已经重写了equals和hashcode方法。

那么,我们下面自定义一下自己的类型看看:

package com.ray.ch15;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;

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 HashSet<SetType>(), SetType.class);
		test(new HashSet<HashType>(), HashType.class);
	}
}

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();
	}
}

输出:

[6, 6, 3, 4, 9, 5, 2, 9, 1, 7, 5, 4, 1, 2, 9, 3, 7, 8, 8, 0, 2, 0, 4, 6, 7, 5, 0, 1, 3, 8]
[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方法


注意点:

(1)从输出我们可以看见,在main的第一个test方法,它的输出是非常多的对象id,而且里面出现了很多的重复,这是因为我们没有重写hashCode方法,在Object的hashCode方法里面,每个对象返回的hashcode都不一样,jvm认定都是不同的对象,因此我们添加多少对象进去,就会显示多少对象

(2)接着上面的解释,下面的HashType重写了hashCode方法,以id为标准,从上面的代码我们可以看见,id非常可能重复,因此jvm就会去重。

我们可以翻开HashSet的源代码,看看add方法:

private transient HashMap<E,Object> map;
public boolean add(E e) {
	return map.put(e, PRESENT)==null;
    }
对象是放到map里面,我们在翻开map的put方法:

public V put(K key, V value) {
        if (key == null)
            return putForNullKey(value);
        int hash = hash(key.hashCode());
        int i = indexFor(hash, table.length);
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }

        modCount++;
        addEntry(hash, key, value, i);
        return null;
    }

它里面是对比了hash值的,因此HashSet想实现去重,必须重写equals和hashcode方法。

(3)由于上面产生的值比较少,因此排序的特殊性没有表露出来,当我们增加创建的对象时,排序就会按照一定的顺序排列,而不是按照我们想象的顺序。关于这种排序,我们后面的章节会说到。下面是例子代码:

package com.ray.ch15;

import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;

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 < 20; 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 HashSet<HashType>(), HashType.class);
	}
}

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();
	}
}

输出:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18]


总结:这一章节主要讲述了使用HashSet需要注意的地方。


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

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

目录









  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值