hashset的使用主要是注意以下几个关键点:
1)hashset可以保证元素唯一,并且能快速查找
2)hashset底层的实现是hashmap(key为set的值,value等于固定的Object对象)
3)hashset支持null元素保存
4)自定义对象作为hashset的值需要重新hashcode和equals方法
5)作为set集合,它可以使用foreach的形式遍历元素,但是无法删除元素,remove时会抛出ConcurrentModificationException异常
6)遍历过程中删除元素,需要使用iterator.remove方法
下面是一些使用相关的代码
package com.basic.util;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class BasicSet {
public static void main(String argv[]) {
Set<SetObject> so = new HashSet<SetObject>();
SetObject sobj = new SetObject("org",3);
so.add(new SetObject("first", 5));
so.add(new SetObject("second", 6));
so.add(new SetObject("org",3));
so.add(sobj);
so.add(null);
Iterator<SetObject> iter = so.iterator();
while (iter.hasNext()) {
SetObject s = iter.next();
if (s != null && s.equals(sobj)) {
iter.remove();
}
}
/*
* 执行会抛出异常
for (SetObject obj : so) {
// 可以添加null元素,所以需要做null判断
if (obj != null && && obj.equals(sobj)) {
so.remove(sobj);
}
}
*/
}
}
class SetObject {
String name;
int length;
public SetObject(String name, int length) {
this.name = name;
this.length = length;
}
@Override
public String toString() {
return this.name + " " + this.length;
}
/*
@Override
public int hashCode() {
int result = 17;
result = 31*result + (name == null ? 0 : name.hashCode());
result = 31*result + length;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof SetObject)) {
return false;
}
SetObject cobj = (SetObject) obj;
if (cobj.length != this.length) {
return false;
}
if (this.name != null) {
if (!this.name.equals(cobj.name)) {
return false;
}
} else {
if (cobj.name != null) {
return false;
}
}
return true;
}
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + length;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof SetObject)) {
return false;
}
SetObject other = (SetObject) obj;
if (length != other.length) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
}
}