您的位置:首页 > 其它

Collection:Set集合

2015-12-03 11:59 197 查看
Collection集合中,除了List集合之外,还有Set集合。Set也是一个接口,使用Set需要实现它,它的常见实现类有HashSet、TreeSet。以常用的HashSet举例。

HashSet:

HashSet实现Set接口,底层以HashMap实现,不保证Set的迭代顺序,即Set是无序不重复的。这儿有一个细节需要注意:HashSet无序可以理解,但是TreeSet是有序的,为什么说Set是无序的呢?这儿有必要对有序这个词进行理解一下。

我们一般说的有序,是指,进入集合的顺序,先加入集合的元素,将先取到。使用迭代器迭代时,是依次去取元素。而TreeSet的有序,是指按自然顺序或者某种规则去排序,用迭代器对它进行迭代时,它取出的数据并不是先加入的先取到,后加入的后取到,而是根据他排序后的顺序去取。所以,可以说Set它是无序的。

HashSet常用的方法和List差不多。主要看一下Set的底层实现原理。

public HashSet() {
map = new HashMap<>();
}
这是HashSet的构造器,可以看到,它是用HashMap去实现的。为什么HashSet会是无序不重复的呢,先看看它的add()方法:

public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
private static final Object PRESENT = new Object();
根据构造器可以看到map是一个HashMap,所以map.put(e, PRESENT)是在HashMap中添加一个元素,它是把对象e作为Map的key,把object作为Map的value,因为Map的键是不重复的,所以HashSet会保证添加的元素是不重复的。
上面说到HashSet是无序且不重复的,但是存储一个对象会不会可以重复呢?用个例子来看一下:

public class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Student() {
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
public class HashSetDemo {
public static void main(String[] args) {
Set<Student> set = new HashSet<Student>();
set.add(new Student("lizy", 23));
set.add(new Student("liyn", 21));
set.add(new Student("lizy", 23));
for (Student student : set) {
System.out.println(student);
}
}
}
运行结果:

Student [name=lizy, age=23]
Student [name=liyn, age=21]
Student [name=lizy, age=23]
上面可以看到,HashSet在添加对象的时候,添加了重复的对象,为什么会重复呢?上面看了它的源码,它底层是以Map来实现的,所以,它的具体操作,要去HashMap中去查看。下面是HashMap的源码:

public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}


final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}


上面HashMap源码,在后期Map中,再详细解释。上面代码大概可以看出,当传入一个对象时,它并不是将对象的值作为主键添加在Map中,而是使用了hashCode()这个方法。它是将对象取hash值,然后做主键的,而在set中添加对象时,每次都是new一个新的对象,所以它们的地址是不同的,因此它们的hash值也是不同的,那么怎么保证它相等呢?
要解决这个,先看影响它的是什么,由源码大概可以看出,要添加一个元素,前面有很多条件,其中hashCode和equals大概可以知道,这两个条件是影响的关键。而hashCode和equals都是Object方法,重写它,如果添加的对象的值完全相同,则返回同一个值:

<span style="white-space:pre">	</span>@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
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 (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
在Student中添加这两个方法,即可解决值全部相同的对象,不被加入到Set集合中。

除了HashSet之外,还有一个TreeSet。TreeSet,它根据自然顺序或者某些指定的条件进行对元素进行排序。TreeSet有两个构造器,一个是无参构造器,另一个是带一个接口的比较器构造器。无参构造器主要以自然顺序去排序。带参构造器,是根基指定的条件去排序。先看看TreeSet的底层实现:

public TreeSet() {
this(new TreeMap<E,Object>());
}
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
根据上面的构造器可以看到,它的底层是以TreeMap来实现的。它的添加方法具体实现代码如下:

public V put(K key, V value) {
Entry<K,V> t = root;<span style="white-space:pre">						</span>//建立根节点
if (t == null) {
compare(key, key); // type (and possibly null) check<span style="white-space:pre">	</span>

root = new Entry<>(key, value, null);<span style="white-space:pre">			</span>//第一次添加数据,将其放入根结点
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;<span style="white-space:pre">				</span>//如果存在参数
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);<span style="white-space:pre">				</span>//比较两个大小
if (cmp < 0)
t = t.left;<span style="white-space:pre">						</span>//小于的,放入左孩子
else if (cmp > 0)
t = t.right;<span style="white-space:pre">					</span>//大于的,放入右孩子
else
return t.setValue(value);
} while (t != null);
}
else {<span style="white-space:pre">								</span>//下面不存在参数的,原理和他一样
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key;
do {
parent = t;
cmp = k.compareTo(t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
Entry<K,V> e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
上面是TreeSet实现底层代码,根据这两个构造器,做一个简单实例:

无参构造器案例:

public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(11);
ts.add(23);
ts.add(13);
ts.add(14);
ts.add(50);
for (Integer integer : ts) {
System.out.print(integer+" ");
}
}
}


输出结果:11 13 14 23 50

带比较器参数构造器案例:
public class TreeSetDemo {
public static void main(String[] args) {
TreeSet<Integer> ts = new TreeSet<Integer>(new Comparator<Integer>() {

@Override
public int compare(Integer o1, Integer o2) {
//倒序排序
return -o1.compareTo(o2);
}
});
ts.add(11);
ts.add(23);
ts.add(13);
ts.add(14);
ts.add(50);
for (Integer integer : ts) {
System.out.print(integer+" ");
}
}
}
输出结果:50 23 14 13 11

上面是TreeSet的底层实现,Tree的实现,可能不是很好理解,下一篇我将把二叉树的构建和三种遍历方式用代码去实现,再回头看它底层实现源码就会熟悉很多。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: