set集合知識

/*算法

* Set:存儲的元素是無序的,不可重複的!ide

*  1.無序性:無序性!= 隨機性。真正的無序性,指的是元素在底層存儲的位置是無序的(存儲時根據hash值隨機存儲)(add一個元素就調用hashCode()方法算出hsah值  不一樣的元素算出的hsah值是不相同的而且是沒有順序 根據hash值給元素指定位置,就像同窗進教室作座位同樣)。性能

* 2.不可重複性:當向Set中添加進相同的元素的時候,後面的這個不能添加進去。new 出來的對象也不行this

 *說明:要求添加進Set中的元素所在的類(自定義類),必定要重寫equals()和hashCode()方法。 進而保證Set中元素的不可重複性!(先算hash值 根據hash值指定位置 ,hash值相同再比較equals()方法)spa

3d

* Set中的元素時如何存儲的呢?使用了哈希算法。指針

* 當向Set中添加對象時,首先調用此對象所在類的hashCode()方法,計算此對象的哈希值,此哈希值,決定了此對象在Set中的存儲位置。若此位置以前沒有對象存儲,則這個對象直接存儲到此位置。若此位置對象

* 已有對象存儲,再經過equals()比較這兩個對象是否相同。若是相同,後一個對象就不能再添加進來。 萬一返回false呢,都存儲。(不建議如此)blog

* >要求:hashCode()方法要與equals()方法一致,(當兩個元素算出同一個hash值時 比較equals(),方法也要爲true)get

*/

@Test

public void testHashSet() {

Set set = new HashSet();

set.add(123);

set.add(456);

set.add(new String("AA"));

set.add(new String("AA"));  //String重寫了兩個方法

set.add("BB");

set.add(null); //能夠存null

Person p1 = new Person("GG", 23);

Person p2 = new Person("GG", 23);

System.out.println(p1.equals(p2));

System.out.println(p1.hashCode());

System.out.println(p2.hashCode());

set.add(p1);

set.add(p2);

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

System.out.println(set);

}


類中重寫

//static int init = 1000;

@Override

public int hashCode() {//return age.hashCode() + name.hashCode();沒下述的健壯性好。

final int prime = 31;

int result = 1;

result = prime * result + ((age == null) ? 0 : age.hashCode());

result = prime * result + ((name == null) ? 0 : name.hashCode());

return result;

//return init++;//不能這樣用

}

@Override

public boolean equals(Object obj) {

if (this == obj)

return true;

if (obj == null)

return false;

if (getClass() != obj.getClass())

return false;

Person other = (Person) obj;

if (age == null) {

if (other.age != null)

return false;

} else if (!age.equals(other.age))

return false;

if (name == null) {

if (other.name != null)

return false;

} else if (!name.equals(other.name))

return false;

return true;

}


/*

* LinkedHashSet:使用鏈表維護了一個添加進集合中的順序。致使當咱們遍歷LinkedHashSet集合

* 元素時,是按照添加進去的順序遍歷的!

* LinkedHashSet插入性能略低於 HashSet,但在迭代訪問 Set 裏的所有元素時有很好的性能。

*/

@Test

public void testLinkedHashSet() {

Set set = new LinkedHashSet();

set.add(123);

set.add(456);

set.add(new String("AA"));

set.add(new String("AA"));

set.add("BB");

set.add(null);

f3953d84dd34f70b6c7242d58af83843.png

存入得位置也是無需  根據算出來的hash值存儲

Iterator iterator = set.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());//鏈表迭代出來的是按照存入得順序(由於鏈表有下標指針,指向下一個元素)

}

}

相關文章
相關標籤/搜索