您好,登錄后才能下訂單哦!
這篇文章主要介紹Java集合框架有什么用,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
概念:對(duì)象的容器,定義了對(duì)多個(gè)對(duì)象進(jìn)行操作的常用方法。可實(shí)現(xiàn)數(shù)組的功能。
集合和數(shù)組的區(qū)別:
數(shù)組長度固定,集合長度不固定
數(shù)組可以存儲(chǔ)基本類型和引用類型,集合只能存儲(chǔ)引用類型。
測(cè)試
/* 1.添加 2.刪除 3.遍歷 4.判斷 */ Collection col = new ArrayList(); col.add("張三"); col.add("李四"); col.add("王五"); // col.add("張三"); System.out.println(col); // col.remove("張三"); // System.out.println(col); for (Object o : col) { System.out.println(o); } System.out.println("------------------"); Iterator it = col.iterator(); while (it.hasNext()){ String next = (String) it.next(); System.out.println(next); } System.out.println(col.isEmpty()); System.out.println(col.contains("張三"));
特點(diǎn):有序、有下標(biāo)、元素可以重復(fù)。
可以通過角標(biāo)在指定位置添加查詢?cè)亍?/p>
List list = new ArrayList(); list.add("java"); list.add("c++"); list.add(1,"python"); list.add(".net"); System.out.println(list.size()); System.out.println(list.toString()); //1.for each遍歷 System.out.println("---------------"); for (Object o : list) { System.out.println(o); } //2.迭代器遍歷 System.out.println("---------------"); Iterator iterator = list.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } //3.list迭代器遍歷 System.out.println("--------正序-------"); ListIterator listIterator = list.listIterator(); while (listIterator.hasNext()){ System.out.println(listIterator.next()); } //逆序前必須先進(jìn)行正序遍歷,讓指針指向列表最后一個(gè)元素,才能開發(fā)遍歷 System.out.println("--------逆序-------"); while (listIterator.hasPrevious()){ System.out.println(listIterator.previousIndex() + ":" +listIterator.previous()); }
添加數(shù)字等基本類型數(shù)據(jù)時(shí),會(huì)進(jìn)行自動(dòng)裝箱的操作。
刪除數(shù)字元素需要通過下標(biāo)來刪除,或者將需要?jiǎng)h除的數(shù)字轉(zhuǎn)成object類或者該類型對(duì)應(yīng)的包裝類。
subList
:返回一個(gè)子集合,含頭不含尾。
List實(shí)現(xiàn)類
數(shù)組存儲(chǔ)結(jié)構(gòu),查詢快、增刪慢;
JDK1.2版本出現(xiàn),運(yùn)行效率快,線程不安全。
源碼分析:
DEFAULT_CAPACITY = 10 默認(rèn)容量 。注意:如果沒有向集合中添加任何元素時(shí),容量為0,添加一個(gè)元素之后,容量為10。每次擴(kuò)容大小都是原來的1.5倍,如添加第11個(gè)元素時(shí),容量由10變?yōu)榱?5。
add()方法源碼:為什么添加一個(gè)元素之后,容量為10。
public boolean add(E e) { ensureCapacityInternal(size + 1); // Increments modCount!!增長修改個(gè)數(shù) elementData[size++] = e; return true; } private void ensureCapacityInternal(int minCapacity) { if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity); } ensureExplicitCapacity(minCapacity); } private void ensureExplicitCapacity(int minCapacity) { modCount++; // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; int newCapacity = oldCapacity + (oldCapacity >> 1); if (newCapacity - minCapacity < 0) newCapacity = minCapacity; if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); // minCapacity is usually close to size, so this is a win: elementData = Arrays.copyOf(elementData, newCapacity); }
elemetnData 存放元素的數(shù)組
size 實(shí)際元素個(gè)數(shù)
測(cè)試代碼:
ArrayList arrayList = new ArrayList(); Student s1 = new Student("張三",18); Student s2 = new Student("李四",18); Student s3 = new Student("王五",18); arrayList.add(s1); arrayList.add(s2); arrayList.add(s3); System.out.println(arrayList.toString()); //刪除元素(需要重寫equals方法) arrayList.remove(new Student("李四",18)); System.out.println(arrayList.size()); public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); }
數(shù)組存儲(chǔ)結(jié)構(gòu),查詢快,增刪慢;
JDK1.0版本出現(xiàn),運(yùn)行效率慢、線程安全;
枚舉器遍歷
Vector vector = new Vector(); vector.add("java"); vector.add("python"); vector.add(".net"); System.out.println(vector.toString()); //枚舉器遍歷 Enumeration elements = vector.elements(); while (elements.hasMoreElements()){ System.out.println(elements.nextElement()); }
雙向鏈表存儲(chǔ)結(jié)構(gòu),增刪快,查詢慢。
時(shí)JDK1.5中引入的一個(gè)新特性,其本質(zhì)是參數(shù)化類型,把類型作為參數(shù)傳遞;
常見形式由泛型類、泛型接口、泛型方法;
好處:
提高代碼的重用性
防止類型轉(zhuǎn)換異常,提高代碼的安全性
泛型集合:參數(shù)化類型、類型安全的集合,強(qiáng)制集合元素的類型必須一致。
特點(diǎn):
編譯時(shí)即可檢查,而非運(yùn)行時(shí)拋出異常。
訪問時(shí),不必類型轉(zhuǎn)換。
不同泛型之間引用不能相互賦值,泛型不存在多態(tài)。
特點(diǎn):無序、無下標(biāo)、元素不可重復(fù)
方法:全部繼承自Collection中的方法。
Set實(shí)現(xiàn)類
存儲(chǔ)結(jié)構(gòu):哈希表(數(shù)組+鏈表+紅黑樹)
基于HashCode實(shí)現(xiàn)元素不重復(fù)
根據(jù)hashcode計(jì)算保存的位置,如果此位置為空,則直接保存。如果不為空,執(zhí)行下一步。
當(dāng)存入元素的哈希碼相同時(shí),會(huì)調(diào)用equals進(jìn)行確認(rèn),如果為true,則拒絕后者存入。否則,則生成鏈表。
public HashSet(){ map = new HashMap<>(); }
測(cè)試代碼:
HashSet<Student> set = new HashSet<>(); Student s1 = new Student("張三",18); Student s2 = new Student("李四",18); Student s3 = new Student("王五",18); set.add(s1); set.add(s2); set.add(s3); // set.add(new Student("李四",18)); System.out.println(set.size()); System.out.println(set.toString()); // set.remove(new Student("李四",18)); // System.out.println(set.size()); // System.out.println(set.toString()); for (Student student : set) { System.out.println(student); } System.out.println("===================="); Iterator<Student> iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name); } public int hashCode() { return Objects.hash(name, age); }
hashcode重寫方法中加入31的原因
1.31是一個(gè)質(zhì)數(shù),減少散列沖突
2.31提高執(zhí)行效率
存儲(chǔ)結(jié)構(gòu):紅黑樹
基于排列順序?qū)崿F(xiàn)元素不重復(fù)
實(shí)現(xiàn)了SortedSet接口,對(duì)集合元素自動(dòng)排序
元素對(duì)象的類型必須實(shí)現(xiàn)Comparable接口,指定排列規(guī)則
通過CompareTo方法確定是否為重復(fù)元素
測(cè)試代碼:使用TreeSet集合實(shí)現(xiàn)字符串按照長度進(jìn)行排序
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int n1 = o1.length() - o2.length(); int n2 = o1.compareTo(o2); return n1==0?n2:n1; } treeSet.add("zhangSan"); treeSet.add("wkf"); treeSet.add("asd"); treeSet.add("abc"); treeSet.add("ljCv"); treeSet.add("liSi"); treeSet.add("wanG"); System.out.println(treeSet.toString()); System.out.println(treeSet.size());
1.用于儲(chǔ)存任意鍵值對(duì)(Key,Value)
2.鍵:無序、無下標(biāo)、不允許重復(fù)
3.值:無序、無下標(biāo)、允許重復(fù)
keySet()方法遍歷:拿到key的set集合。
entrySet()方法遍歷:將map封裝成entry鍵值對(duì)集合。
測(cè)試代碼:
Map<String, String> map = new HashMap<>(); map.put("wkf","666"); map.put("qwe","678"); map.put("kfc","999"); map.put("asd","694"); Set<String> keySet = map.keySet(); for (String s : keySet) { System.out.println(s + "=" + map.get(s)); } System.out.println("==================="); Set<Map.Entry<String, String>> entries = map.entrySet(); for (Map.Entry<String, String> entry : entries) { System.out.println(entry.getKey() +"=" + entry.getValue() ); }
JDK1.2版本,線程不安全,運(yùn)行效率快;允許用null作為key或是value。
構(gòu)造一個(gè)具有默認(rèn)初始容量16和默認(rèn)加載因子0.75的空HashMap。
加載因子:比如當(dāng)前集合容量為100,那么當(dāng)數(shù)據(jù)存儲(chǔ)到第75個(gè)位置是進(jìn)行擴(kuò)容操作。
源碼分析
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // hashMap初始容量大小16 static final int MAXIMUM_CAPACITY = 1 << 30;//hashMap的數(shù)組最大容量 static final float DEFAULT_LOAD_FACTOR = 0.75f;//默認(rèn)加載因子 static final int TREEIFY_THRESHOLD = 8;//jdk1.8開始,當(dāng)鏈表長度大于8時(shí),調(diào)整成紅黑樹 static final int UNTREEIFY_THRESHOLD = 6;//jdk1.8開始,當(dāng)鏈表長度小于6時(shí),調(diào)整成鏈表 static final int MIN_TREEIFY_CAPACITY = 64;//jdk1.8開始,當(dāng)鏈表長度大于8時(shí),并且集合元素個(gè)數(shù)大于等于64時(shí)調(diào)整成紅黑樹 transient Node<K,V>[] table;//哈希表中的數(shù)組
總結(jié):
HashMap剛創(chuàng)建時(shí),table是null,為了節(jié)省空間,當(dāng)添加第一個(gè)元素時(shí),table容量調(diào)整為16
當(dāng)元素個(gè)數(shù)大于閾值(16*0.75=12)時(shí),會(huì)進(jìn)行擴(kuò)容,擴(kuò)容后大小為原來的兩倍。目的是減少調(diào)整元素的個(gè)數(shù)
jdk1.8開始,當(dāng)鏈表長度大于8時(shí),并且集合元素個(gè)數(shù)大于等于64時(shí)調(diào)整成紅黑樹,目的是提高執(zhí)行效率
jdk1.8開始,當(dāng)鏈表長度小于6時(shí),調(diào)整成鏈表
jdk1.8以前,鏈表時(shí)頭插入,jdk1.8以后是尾插入
JDK1.0版本,線程安全,運(yùn)行效率慢;不允許null作為key或是value
Properties:
Hashtable的子類,要求key和value都是String,通常用于配置文件的讀取。
實(shí)現(xiàn)了SortedMap接口(是Map的子接口),可以對(duì)key自動(dòng)排序。
Collections工具類
sort():升序排列
copy():復(fù)制
binarySearch():二分查找
Collections.binarySearch(list,需要查找的值);
reverse():反轉(zhuǎn)
shuffle():打亂集合中的元素
list轉(zhuǎn)成數(shù)組:
list.toArray(new Integer[0]);
數(shù)組轉(zhuǎn)成集合
Arrays.asList(names);
集合是一個(gè)受限集合,不能添加 和
以上是“Java集合框架有什么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。