JavaSE collection class

  • An overview of the
    • Overview of collection classes in Java
    • Contrast arrays with collections in Java
    • A collection framework hierarchy in Java
  • The Collection interface
    • Common methods of Collection interface
  • The Set interface
  • The List interface
    • List interface common methods
    • ArrayList
    • LinkedList
  • The Map interface
    • Common Map interface methods
    • A HashMap class
    • Comparison of HashMap and TreeMap
    • Comparison of HashMap and Hashtable

An overview of the

Overview of collection classes in Java

A collection class in Java is a collection that holds objects. It is a container that contains a set of objects — each object of the container class appears as an element of the collection. The Java API provides collection classes in the java.util package

Contrast arrays with collections in Java

Arrays are containers, they’re fixed size, they’re fast to access, but arrays don’t automatically scale arrays can contain objects of primitive data types or reference types, whereas collections can only contain objects of reference types

A collection framework hierarchy in Java

The Collection interface

· A Set of objects called elements · A Collection can hold different types of data · It is the parent of the Set and List interfaces · Whether there is a specific order and whether repetition is allowed depends on its implementation of set-unordered collections; No duplicates (HashSet) List – ordered collection; Allow repetition (ArrayList, LinkedList)

Common methods of Collection interface

methods meaning
boolean add(Object) Adds an object to the collection, returning true on success
boolean addAll(Collection) Adds another collection object to the collection
int size() The number of elements in a collection
boolean isEmpty() Whether the set is empty
boolean contains(Object) Whether the collection contains parameter objects
Iterator iterator() Produces an iterator
Object[] toArray() Returns an array of objects containing all elements
boolean remove(Object) Removes objects from the collection
boolean removeAll(Collection) Clear the specified collection
boolean containsAll(Collection) Determine whether the set contains subsets
boolean retainAll(Collection) Only those elements from this collection that are also included in the specified collection are retained

The Set interface

Set interface · Sub-interface of Collection · Used to contain an unordered Set of non-repeating objects unordered — the order in which elements are stored differs from the order in which they are stored in the Collection; No duplication – Two objects E1 and e2, if e1.equals(e2) returns true, e1 and e2 are considered to be duplicated and only one is retained in the set. TreeSet — TreeSet stores in a different order than TreeSet stores in a different order, but TreeSet stores in a sorted order, traversing sets in a foreach fashion

Sample code:

package com.training.csdn; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Keafmd ** @className: MySet * @description: Set explanation * @author: Public class MySet {public static void main(String[] args) {public static void main(String[] args) {Set Set = new HashSet(); //add set.add(50); set.add(60); //int Integer set.add(200); set.add(new Integer(200)); System.out.println("set.size() : "+set.size()); Set set2 = new HashSet(); set2.addAll(set); System.out.println("set2.size() : "+set2.size()); System.out.println(" set2.isempty () : "+ set2.isempty ()); Println ("set2.contains(60) : "+set2.contains(60)); system.out. println("set2.contains(60) : "+set2.contains(60)); Println ("set2.contains(200) : "+set2.contains(new Integer(200))); println("set2.contains(200) : "+set2.contains(new Integer(200))); Set Iterator it = set2. Iterator (); while(it.hasNext()){ Object item = it.next(); System.out.println(" element: "+item); } // Remove the element set.remove(50) by equals and hashcode; System.out.println(" Number of elements removed: "+set.size()); Set set3 = new HashSet(); set3.add("abc"); set3.add("def"); set3.add("ghi"); set3.add("aaa"); Set set4 = new HashSet(); set4.add("abc"); set4.add("def"); set4.add("kkk"); set4.add("aaa"); System. The out. Println (" set3. Size: "+ set3. The size ()); Set3. removeAll(set4); // system.out.println (" set length: "+set3.size()); // // // for (Object o: set3) {// system.out.println ("set3's element has: "+o); } // keep the intersection of set3 and set4 element set3.retainAll(set4); System. The out. Println (" retainAll. Size: "+ set3. The size ()); For (Object o: set3) {system.out.println ("set3's element has: "+o); } // Clear the set set3.clear(); System.out.println(set3.size()); / / 0}}Copy the code

Operation effect:

Set.size () : 3 set2.size() : 3 set2.isempty () : false set2.contains(60) : true set2.contains(200) : true element: 50 element: 200 element: Size: 4 retainall. size: 3 Set3 elements: aaa set3 elements: ABC set3 elements:  def 0 Process finished with exit code 0Copy the code

The List interface

List interface common methods

methods meaning
void add(int index,Object element) In the index position of the list, add the element Element
Object get(int index) Returns the element in the list at the specified position
int indexOf(Object o) Query the index value of the element in the list, if not present, return -1.
int lastIndexOf(Object o) IndexOf () if there are multiple duplicate elements in a List
ListIterator listIterator() Returns a list iterator for the elements in the list
Object remove(int index) Removes the element at the specified position in the list
Object set(int index,Object element) Replaces the element at the specified position in the list with the specified element

ArrayList vs. LinkedList: Storage structure: ArrayList is linear sequential storage. LinkedList A list of objects that are linked to each other. Performance: ArrayList is suitable for random queries. LinkedList elements can be inserted and deleted easily. LinkedList is a little bit more.

ArrayList

Explain the code:

package com.CSDN.day26; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Keafmd ** @className: MyArrayList * @description: ArrayList * @author: 2020/11/26 21:01 **/ public class MyArrayList { public static void main(String[] args) { // List list1 = new ArrayList(); List1. Add (" * * "); List1. Add (" li si "); List1. Add (" li si "); List1. Add (" detective "); System.out.println("list1.size()\t"+list1.size()); List list2 = new ArrayList(list1); System.out.println("list2.size()\t"+list2.size()); System.out.println("========================================================"); // system.out. println("list1.get(0)\t"+list1.get(0)); // System.out.println("list1.get(1)\t"+list1.get(1)); // System.out.println("list1.get(2)\t"+list1.get(2)); for (int i = 0; i < list1.size(); i++) { System.out.println("list1.get("+i+")\t"+list1.get(i)); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = enhancement for traversing the = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); for (Object o : list2) { System.out.println("item\t"+o); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = Iterator traverses the = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); for(Iterator it = list2.iterator(); it.hasNext() ; ) { System.out.println("iterator Item \t"+it.next()); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = forEach traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); // list2.forEach(System.out::println); list2.forEach(x->System.out.println("forEach item\t"+x)); System.out.println("=======================add(index,Object el)================================="); List list3 =new ArrayList(); list3.add("abc"); list3.add("def"); list3.add("jqk"); //list3 add(index ,el) list3.add(1,"insert"); list3.forEach(x->System.out.println("list3 item\t"+x)); System.out.println("=======================add(index,Object el)================================="); //list3 update(index ,el) list3.set(1,"update"); list3.forEach(x->System.out.println("list3 item\t"+x)); Println (" list3.indexof (\"def\")\t"+ list3.indexof ("def")); If (list3.indexof ("def")! = list3.lastIndexof ("def")){system.out.println ("def"); } //listIterator ListIterator listIter = list3.listIterator(list3.size()-1); while (listIter.hasPrevious()){ System.out.println("listIter.previous()\t"+listIter.previous()); }}}Copy the code

Running results:

List2 list1. The size () 4. The size (4) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = list1. Get (0) zhang SAN list1. Get (1) the bill List1. Get (2) li si list1. Get (3) fifty = = = = = = = = = = = = = = = = = = = = = = = enhancement for traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = item item zhang SAN li si item li si Item fifty = = = = = = = = = = = = = = = = = = = = = = = Iterator traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Iterator item zhang SAN Iterator item li si Iterator Item li si iterator Item fifty = = = = = = = = = = = = = = = = = = = = = = = forEach traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = forEach Item zhang SAN forEach Item Li si forEach item li si forEach item fifty = = = = = = = = = = = = = = = = = = = = = = = add (index, Object el) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = list3 item abc list3 item insert list3 item def list3 item jqk =======================add(index,Object el)================================= list3 item abc list3 item update list3 item def list3 item jqk list3.indexOf("def")  2 listIter.previous() def listIter.previous() update listIter.previous() abc Process finished with exit code 0Copy the code

LinkedList

Explain the code:

package com.CSDN.day26; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; /** * Keafmd ** @className: MyLinkedList * @description: LinkedList * @author: Cow cow conan * @date: 2020/11/26 21:06 **/ public class MyLinkedList { public static void main(String[] args) { // List list1 = new LinkedList(); List1. Add (" * * "); List1. Add (" li si "); List1. Add (" li si "); List1. Add (" detective "); System.out.println("list1.size()\t"+list1.size()); List list2 = new LinkedList(list1); System.out.println("list2.size()\t"+list2.size()); System.out.println("========================================================"); // system.out. println("list1.get(0)\t"+list1.get(0)); // System.out.println("list1.get(1)\t"+list1.get(1)); // System.out.println("list1.get(2)\t"+list1.get(2)); for (int i = 0; i < list1.size(); i++) { System.out.println("list1.get("+i+")\t"+list1.get(i)); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = enhancement for traversing the = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); for (Object o : list2) { System.out.println("item\t"+o); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = Iterator traverses the = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); for(Iterator it = list2.iterator(); it.hasNext() ; ) { System.out.println("iterator Item \t"+it.next()); } System. Out. Println (" = = = = = = = = = = = = = = = = = = = = = = = forEach traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); // list2.forEach(System.out::println); list2.forEach(x->System.out.println("forEach item\t"+x)); System.out.println("=======================add(index,Object el)================================="); List list3 =new LinkedList(); list3.add("abc"); list3.add("def"); list3.add("jqk"); //list3 add(index ,el) list3.add(1,"insert"); list3.forEach(x->System.out.println("list3 item\t"+x)); System.out.println("=======================add(index,Object el)================================="); //list3 update(index ,el) list3.set(1,"update"); list3.forEach(x->System.out.println("list3 item\t"+x)); Println (" list3.indexof (\"def\")\t"+ list3.indexof ("def")); If (list3.indexof ("def")! = list3.lastIndexof ("def")){system.out.println ("def"); } System.out.println("================================================"); ListIterator listIter = list3.listIterator(); while (listIter.hasNext()){ System.out.println("listIter.next()\t"+listIter.next()); } System.out.println("============================="); //listIterator // ListIterator listIter2 = list3.listIterator(list3.size()); // while (listIter2.hasPrevious()){ // System.out.println("listIter2.previous()\t"+listIter2.previous()); // } LinkedList lList = new LinkedList(); lList.addAll(list3); Object popItem = lList.pop(); PollItem = llist.poll (); pollItem = llist.poll (); System.out.println(pollItem); }}Copy the code

Running results:

List2 list1. The size () 4. The size (4) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = list1. Get (0) zhang SAN list1. Get (1) the bill List1. Get (2) li si list1. Get (3) fifty = = = = = = = = = = = = = = = = = = = = = = = enhancement for traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = item item zhang SAN li si item li si Item fifty = = = = = = = = = = = = = = = = = = = = = = = Iterator traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = Iterator item zhang SAN Iterator item li si Iterator Item li si iterator Item fifty = = = = = = = = = = = = = = = = = = = = = = = forEach traversal = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = forEach Item zhang SAN forEach Item Li si forEach item li si forEach item fifty = = = = = = = = = = = = = = = = = = = = = = = add (index, Object el) = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = list3 item abc list3 item insert list3 item def list3 item jqk =======================add(index,Object el)================================= list3 item abc list3 item update list3 item def list3 item jqk list3.indexOf("def")  2 ================================================ listIter.next() abc listIter.next() update listIter.next() def listIter.next() jqk ============================= update Process finished with exit code 0Copy the code

The Map interface

Map stores key/value pairs so that pairs of object groups (you can think of a group of objects as an element) can be queried by “key” objects. Map is another Collection interface that is different from Collection. In a Map, the key value is unique (it cannot be repeated) and the key object is associated with the value object. The Map interface has two implementations: The Hashmap-key /value pair is stored according to the Hash algorithm. TreeMap — Key /value pairs are stored by sort (sort by key).

Common Map interface methods

methods meaning
Object put(Object key,Object value) Associates the specified value with the specified key in this mapping
void putAll(Map t) Copy all mappings in mapping T into this mapping
Object get(Object key) Returns the value mapped to the specified key in this mapping
Object remove(Object key) If there is a mapping for this key, remove it from the mapping
boolean containsKey(Object key) Returns true if this mapping contains the mapping of the specified key
boolean containsValue(Object value) Returns true if this mapping maps one or more keys to the specified value
int size() Returns the key-value mapping logarithm in this mapping
void clear() Removes all mappings from this mapping
boolean isEmpty() Returns true if this mapping does not contain a key-value mapping
Set keySet() Returns the set view of the keys contained in this map

A HashMap class

The HashMap class is an implementation of the Map interface based on a hash table

Student class:

package com.CSDN.day26; /** * Keafmd ** @className: Student * @description: * @author: @date: 2020/11/26 21:16 **/ public class Student { String name; int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = 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; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code

Explain the code:

package com.CSDN.day26; import java.util.*; /** * Keafmd ** @className: MyMap * @description: Map * @author: 2020/11/26 21:15 **/ public class MyMap {public static void main(String[] args) {// Create object Map<String,Student> Map = new  HashMap<>(); List<Student> stuList = new ArrayList(); Stulist. add(new Student("张飞",50)); Stulist. add(new Student("张飞1",36)); Stulist. add(new Student("张飞2",20)); Stulist. add(new Student("张飞3",58)); // If you want to find an attribute of an element, you need to iterate through the set to find the element. Println ("student.age\t"+ student.getage ()); stuList) {if(" equals(student.getName())){system.out.println ("student.age\t"+ student.getage ()); break; }} //put key cannot repeat map.put(" zhang Fei ",new Student(" Zhang Fei ",50)); Map. Put (" zhangfei 1",new Student(" Zhangfei 1",36)); Map. Put (" zhangfei 2",new Student(" Zhangfei 2",20)); Map. Put (" zhangfei 3",new Student(" zhangfei 3",58)); Student stu = (Student) map.get(" zhang Fei-3 "); //get (Student stu = (Student) map.get(" zhang Fei-3 ")); System.out.println(stu.getAge()); /** * int size() * void clear() * boolean isEmpty() */ // map.clear(); System.out.println("map.size\t"+map.size()); System.out.println("map.isEmpty\t"+map.isEmpty()); Map map2 = new HashMap(); Map2. put(" zhangfei3 ",new Student(" zhangfei3 ",999)); Map2. Put (" zhangfei4 ",new Student(" zhangfei4 ",20)); Student zf5 = new Student(" zf5 ", 58); Map2. Put (" 5 "zhang fei, zf5); map.putAll(map2); System.out.println("map.size\t"+map.size()); System. Out. Println (" map. Get (\ "zhang fei 3 \" \ t "+ map. Get (" zhang fei 3"). GetAge ()); System.out.println("map.containsKey(\" \")\t"+map.containsKey(" \")); System.out.println("map.containsKey(\" zhangfei99 \")\t"+map.containsKey(" zhangfei99 ")); Println ("map.containsValue(new Student(\" zhangfe5 \",58)\t"+map.containsValue(zf5)); println("map.containsValue(new Student(\" zhangfe5 \",58)\t"+map.containsValue(zf5)); System.out.println("========================size=============================="); System.out.println("map.size\t"+map.size()); Map. Remove (" zhang fei 3 "); System.out.println("map.size\t"+map.size()); //HashMap traversal Set<String> keySet = map.keyset (); for (String key : keySet) { System.out.printf("key:%s\tvalue:%s\r\n",key,map.get(key).toString()); } System.out.println("================================================"); Set<Map.Entry<String, Student>> entrySet = map.entrySet(); for (Map.Entry<String, Student> stringStudentEntry : entrySet) { String key = stringStudentEntry.getKey(); Student value = stringStudentEntry.getValue(); System.out.printf("key:%s\tvalue:%s\r\n",key,value.toString()); }}}Copy the code

Running results:

Size 4 map.isEmpty false map.size 6 map.get(" zhang Fei 3") 999 map.containsKey(" Zhang Fei ") true Map. containsKey(" Zhangfei 99") false map.containsValue(new Student(" Zhangfei 5",58) true = = = = = = = = = = = = = = = = = = = = = = = = size = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = map. The size 6 map. The size 5 key: zhang fei value: Student {name = 'zhang fei, 5', Age =58} key: Student{name=' Student ', age=20} key: Student{name=' Student ', Age =50} key: Student{name=' Student ', age=20} key: Student{name=' Student ', Age 36} = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = key: zhang fei value: Student {name = 'zhang fei, 5', Age =58} key: Student{name=' Student ', age=20} key: Student{name=' Student ', Age =50} key: Student{name=' Student ', age=20} key: Student{name=' Student ', age=36} Process finished with exit code 0Copy the code

Comparison of HashMap and TreeMap

HashMap is implemented based on hash tables. TreeMap is implemented based on trees. HashMap can optimize the use of HashMap space by tuning the initial capacity and load factor. There is no tuning option for TreeMap because the tree is always in balance.

Comparison of HashMap and Hashtable

Hashtable is based on the old Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2. Hashtable is thread-safe, that is, synchronous, whereas HashMap is threadunsafe, not synchronous. A HashMap allows NULL as an entry key or value, whereas a Hashtable does not allow NULL.

If it helps you, thank you for your support!