文章目錄
1.集合和數組的區別?
A:長度區別
數組固定
集合可變
B:內容區別
數組可以是基本類型,也可以是引用類型
集合只能是引用類型
C:元素內容
數組只能存儲同一種類型
集合可以存儲不同類型(其實集合一般存儲的也是同一種類型)
2. Collection特點
3.Collection和Map接口
Java集合中List,Set以及Map等集合體系詳解(史上最全)
- List , Set, Map都是接口,前兩個繼承至Collection接口,Map爲獨立接口
Set
下有HashSet,LinkedHashSet,TreeSetList
下有ArrayList,Vector,LinkedListCollection
接口下還有個Queue接口,有PriorityQueue類Map
下有Hashtable,LinkedHashMap,HashMap,TreeMap
4. TreeSet, LinkedHashSet and HashSet 的區別
TreeSet的主要功能用於排序
LinkedHashSet的主要功能用於保證FIFO即有序的集合(先進先出)
HashSet只是通用的存儲數據的集合
5. Collection和Collections的區別
Collection 是單列集合的頂層接口,有兩個子接口List和Set
Collections 是針對集合進行操作的工具類,可以對集合進行排序和查找等,都是靜態方法
6. HashSet保證元素唯一性
6.1 原理
class HashSet implements Set {
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
public HashSet() {
map = new HashMap<>();
}
public boolean add(E e) { //e=hello,world
return map.put(e, PRESENT)==null;
}
}
class HashMap implements Map {
public V put(K key, V value) { //key=e=hello,world
//看哈希表是否爲空,如果空,就開闢空間
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//判斷對象是否爲null
if (key == null)
return putForNullKey(value);
int hash = hash(key); //和對象的hashCode()方法相關
//在哈希表中查找hash值
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
//這次的e其實是第一次的world
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {//判斷
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
//走這裏其實是沒有添加元素
}
}
modCount++;
addEntry(hash, key, value, i); //把元素添加
return null;
}
transient int hashSeed = 0;
final int hash(Object k) { //k=key=e=hello,
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode(); //這裏調用的是對象的hashCode()方法
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
}
觀察源碼可知,hashset實際上使用hashmap的put方法,關鍵比較:
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
add方法底層主要依賴兩個方法:hashCode()
和equlas()
。
先判斷hashCode()值是否相同:
- 相同:繼續判斷equlas()方法。
– true:重複,不添加
– false:不重複,添加 - 不相同:直接添加
6.2 相同的字符串只存儲一個
String類重寫了hashCode()和equals()方法,所以,它就可以把內容相同的字符串去掉。只留下一個。
6.3 相同的自定義對象只存儲一個
自定義類沒有重寫這兩個方法,默認使用的Object()。一般來說不相同,默認會存儲。故需要重寫。
public class Person {
private String name;
private Integer age;
public Person(String name,Integer age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj) {
if(this == obj){//地址相同
return true;
}
if (!(obj instanceof Person)) {//是否是當前類的實例
return false;
}
Person s = (Person)obj;//是當前類的實例額,再繼續比較屬性
return this.name.equals(s.name)&& this.age == s.age;
}
@Override
public int hashCode() {
// 引用類型使用hashCode(),整型直接使用
return this.name.hashCode()+this.age;
}
}
7. TreeSet實現元素排序
7.1 原理
class TreeMap implements NavigableMap {
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
// split comparator and comparable paths
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = t;
cmp = cpr.compare(key, t.key);
if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);
} while (t != null);
}
else {
if (key == null)
throw new NullPointerException();
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;
}
}
class TreeSet implements Set {
private transient NavigableMap<E,Object> m;
public TreeSet() {
this(new TreeMap<E,Object>());
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
}
通過觀察TreeSet的add()方法,我們知道最終要看TreeMap的put()方法。
真正的比較是依賴於元素的compareTo()方法,而這個方法是定義在 Comparable裏面的。
所以,你要想重寫該方法,就必須是先實現 Comparable接口。這個接口表示的就是自然排序。
7.2 自然排序
常見的包裝類型:已實現Comparable接口,可以進行自然排序;
自定義類:需要自己實現Comparable接口。
public class Student implements Comparable<Student> {
@Override
public int compareTo(Student s) {
// return 0; 指添加第一個元素
// return 1; 順序
// return -1; 逆序
// 這裏返回什麼,其實應該根據我的排序規則來做
// 按照年齡排序,主要條件
int num = this.age - s.age; // 大於0,升序
// 次要條件
// 年齡相同的時候,還得去看姓名是否也相同
// 如果年齡和姓名都相同,纔是同一個元素
int num2 = num == 0 ? this.name.compareTo(s.name) : num;
return num2;
}
7.3 比較器排序
需要構造器的實現類作爲集合對象構造函數的參數。可以使用匿名內部類。
創建集合對象:
TreeSet<Student> ts = new TreeSet<Student>(); //自然排序
public TreeSet(Comparator comparator) //比較器排序
TreeSet<Student> ts = new TreeSet<Student>(new MyComparator()); // 需要使用帶比較器的構造方法
定義構造器是實現類:
public class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
// 姓名長度
int num = s1.getName().length() - s2.getName().length();
// 姓名內容
int num2 = num == 0 ? s1.getName().compareTo(s2.getName()) : num;
// 年齡
int num3 = num2 == 0 ? s1.getAge() - s2.getAge() : num2;
return num3;
}
}
8. Map集合的遍歷
(1)鍵找值
(2)鍵值對對象找鍵和值
Map<String,String> hm = new HashMap<String,String>();
hm.put("it002","hello");
hm.put("it003","world");
hm.put("it001","java");
//方式1 鍵找值
Set<String> set = hm.keySet();
for(String key : set) {
String value = hm.get(key);
System.out.println(key+"---"+value);
}
//方式2 鍵值對對象找鍵和值
Set<Map.Entry<String,String>> set2 = hm.entrySet();
for(Map.Entry<String,String> me : set2) {
String key = me.getKey();
String value = me.getValue();
System.out.println(key+"---"+value);
}
9.Hashtable和HashMap的區別
- Hashtable:線程安全,效率低。不允許null鍵和null值
- HashMap:線程不安全,效率高。允許null鍵和null值