Hashset 常用的方法

package com.hu.cool;

import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.junit.Test;

public class Hashset {
/*
* 哈希算法
* 在像Set中添加对象的时候首先对用该对象的hashcode()方法计算出该对象的hashcode值
* 此值决定了对象在set中的存贮位置若位置已经存在对象;则需要调用equals方法来进行比较
* 如果相同则后一个不再插入进去。
*/

@Test
public void test() {
HashSet hashSet=new HashSet<>();
hashSet.add(234);
hashSet.add(new String("AA"));
hashSet.add(456);
hashSet.add("BB");
hashSet.add(null);
Person person=new Person("yongyuan", 14);
Person person2=new Person("yongyuan", 14);
//在进行是否相同的判断的时候必须重写equals()和hashcode()方法
//而List的时候只需要重写equals方法就可以。
hashSet.add(person);
hashSet.add(person2);

System.out.println(hashSet.size());
System.out.println(hashSet);

}
@Test
public void Linkedhashset(){
Set set=new LinkedHashSet<>();
set.add(234);
set.add(456);
set.add("aa");
set.add("bb");
set.add(null);
Person person=new Person("yongyuan", 14);
Person person2=new Person("yongyuan", 14);
set.add(person2);
set.add(person);
System.out.println(set.size());
System.out.println(set);
}
//有序还是无序是针对存储而不是遍历,遍历的时候都是有序的
//linkedhashset 插入的时候性能要地狱hashset但是迭代遍历的时候性能明显要比较高
@Test
public void TreeSet(){
/*//set.add("aa");添加的类型必须和之前的兼容不然会报错
* 遍历的时候没有按照添加的顺序排列而是按照字母的顺序进行排序
*
*/
Set set=new java.util.TreeSet();
/*set.add("AA");
set.add("AA");
set.add("ABB");
set.add("GG");
set.add("MM");
set.add("KKA");
*/
//添加自定义类的时候需要重写comparable接口
//进行插入的时候只要是有属性值不一样就不能插入,只能插入第一个当然可以自己写comparable实现的方法来改写
set.add(new Person("GG", 34));
set.add(new Person("AA", 24));
set.add(new Person("BB", 34));
set.add(new Person("JJ", 34));
System.out.println(set.size());
for (Object object : set) {
System.out.println(object);
}
}

}

**************************************************************************

Treeset的定制排序的方法

@Test
public void test3(){
//实现了一个叫comparatoe的对象
Comparator comparator=new Comparator() {

@Override
//在Treeset中创建custoer对象,并指明按照customer的那个属性来进行比较排序
public int compare(Object o1, Object o2) {
if(o1 instanceof Customer && o2 instanceof Customer){
Customer customer1=(Customer) o1;
Customer customer2=(Customer) o2;
//下面这段代码可以保证当比较的属性相同的时候可以用其他属性来进行比较。
int i= customer1.getAgeInteger().compareTo(customer2.getAgeInteger());
if(i==0){
return customer1.getNameString().compareTo(customer2.getNameString());
}else{
return i;
}
}
return 0;
}
};
//将次对象作为形参传递给treeset 对象
java.util.TreeSet set=new java.util.TreeSet(comparator);
//向Treeset中添加Comparator接口中compare方法中实现的对象
set.add(new Customer("AA", 1003));
set.add(new Customer("BB", 1001));
set.add(new Customer("CC", 1007));
set.add(new Customer("DD", 1003));
set.add(new Customer("EE", 1006));

for (Object object : set) {
System.out.println(object);
}

}

原文地址:https://www.cnblogs.com/afterhours/p/6134009.html