1.hashmap
实现map接口,按键值对存储,按键计算hash值,可直接用key值获取value对象,比较方便。
存放数字时无序,不可重复key值
2.hashset
从以下源码可以看出hashset是基于hashmap实现的,可以把它当成一个value为空的hashmap,是对hashmap的封装和利用。实现set接口,按对象存储,按存储对象计算hash值,要全部迭代才能一一读出对象。
存放数字时无序,不可重复值
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
static final long serialVersionUID = -5024744406713321676L;
private transient HashMap<E,Object> map;
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
public Iterator<E> iterator() {
return map.keySet().iterator();
}
public int size() {
return map.size();
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean contains(Object o) {
return map.containsKey(o);
}
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
public void clear() {
map.clear();
}
}
3.collection
数据集合的基本接口有两种,collection和map。实现collection接口的子接口有Set,List,Queue,他们的实现类应该很清楚了,是我们常用的hashset,arraylist等,collection是它们的公共接口。而这里想提到的是collection中的三个易混淆方法retainAll,containsAll和removeAll:
boolean retainAll(Collection<?> c)
:调用此方法除去collection中不存在于c中的元素。换句话说,如果collection中的元素在c中没有找到,则会去掉collection中的这一元素,并且返回true(collection被改变则会返回true);如果collection中的所有元素在c中都可以找到,则不会改变collection并且返回false。这里也就是相当于一个另类的求两个集合的交集。
例如:
c1: 1,2,2
c2: 1,2
c1.retainAll(c2);//这里会返回false,因为c1中的元素在c2中都存在,不需要改变,则返回false
boolean containsAll(Collection<?> c)
:调用此方法判断collection是否包含c中的所有元素
boolean removeAll(Collection<?> c)
:调用此方法去掉所有collection中存在于c中的元素,和retainAll差不多,如果colletion没有改变,则返回false,否则返回true。这里也就是相当于一个另类的求两个集合的差集。
例如:
c1: 1,2,2,3
c2: 1,2
c1.removeAll(c2);//这里会返回true,因为c1中的元素在c2中都存在,c1中的元素除了3之外会被全部移除,c1最后输出只有3