Summary of the collection

A Java collection is like a container, and these objects can be of any data type and of variable length. According to its storage structure, Collection can be divided into two categories, namely, single-column Collection and double-column Collection Map. The features of the two collections are as follows: (1) Collection: Single-column Collection interface for storing a series of elements. The Collection Collection has two important subinterfaces, List and Set. The feature of List set is that the elements are ordered and repeatable. A Set is characterized by elements that are unordered and non-repeatable. The main implementation classes of the List interface are ArrayList and ListedList. The main implementation classes of the Set interface are HashSet and TreeSet. (2) Map: the root interface of the two-column set, which is used to store elements with Key and Value mappings. Each element in a Map set contains a pair of Key values, and the Key is unique. When using a Map set, you can find the corresponding Value by referring to the Key. The main implementation classes of the Map interface are HashMap and TreeMap.

The List interface

The List interface inherits from the Collection interface. Duplicate elements are allowed in the List. In the program, the specified elements in the List can be accessed through the index.

ArrayList collection

An ArrayList encapsulates an array object of variable length (the initial size is 8, multiplied by 1.5 times). Adding, deleting, modifying and searching in an ArrayList is inefficient, but it is very efficient in traversing and searching elements. To overcome the problem of low efficiency in addition and deletion of ArrayList, we can use LinkedList, which has a bidirectional circular LinkedList and is highly efficient in addition and deletion.

Collection Traversal of the Collection

Iterator iterates through a collection

Iterator objects are called iterators and are used to access elements in a Collection. When iterating over a collection element using an iterator, an exception occurs if the remove method is called to remove the element. The reason is that deleting elements in the set will change the number of iterations of the iterator tone, resulting in inaccurate results of the iterator.

Public class Test1 {public static void main(String[] args) {// Create ArrayList object ArrayList = new ArrayList(); // Add element list.add("data_1"); list.add("data_2"); list.add("data_3"); Iterator iterator = list.iterator(); While (iterator.hasnext ()){//hasNext() determines whether the next element in the set exists. Object Object = iterator.next(); // If it exists, call next() to fetch it, otherwise the end of the collection has been reached, stop traversing System.out.println(object); }} // The output is data_1 data_2 data_3Copy the code

Foreach traverses the collection

Foreach is a brief for loop, also known as an enhanced FOR loop. The foreach loop is used to iterate over the elements of a set or collection in the following syntax

For (Element type temporary variable in container: Public class Test1 {public static void main(String[] args) {ArrayList list = new ArrayList(); // Add element list.add("data_1"); list.add("data_2"); list.add("data_3"); for (Object object : list) { System.out.println(object); }}}Copy the code

Foreach was also limited in that you could not modify the elements in the collection when using foreach loops.

ForEach traversal collection for JDK8

In JDK8, following the nature of Lambda expressions, a forEach method is added to traverse collections, as illustrated below

Public class Test1 {public static void main(String[] args) {// Create ArrayList object ArrayList = new ArrayList(); // Add element list.add("data_1"); list.add("data_2"); list.add("data_3"); List. ForEach (obj-> system.out.println (" iterator set element "+obj)); Iterator set data_1 iterator set data_2 iterator set data_3Copy the code

The Set interface

Set Interface Introduction

Elements in the Set interface are out of order and are guaranteed not to be stored twice. The Set interface mainly has two implementation classes, namely HashSet and TreeSet. HashSet determines the storage location in the element Set according to the hash value of the object, so it has good access and lookup performance. TreeSet stores elements as a binary tree that sorts the elements in a collection.

HashSet collection

A HashSet is an implementation class of the SET interface that stores elements that are not repeatable and are unordered. When you want to add an element to a HashSet collection, the HashCode method is first called to determine where the element is stored, and then the equals () method of the element object is called to ensure that there are no duplicate elements at that location.

public class Test1 { public static void main(String[] args) { HashSet hashSet = new HashSet(); hashSet.add("Jack"); hashSet.add("Rose"); hashSet.add("Eve"); hashSet.add("Rose"); hashSet.forEach(obj-> System.out.println(obj)); }} // The output is Eve Rose JackCopy the code

To ensure that a HashSet works properly when storing elements to a collection, you need to override the hashCode () and equals () methods in the Object class before storing objects. In the previous example, the String class overrides the methods of hashCode by default when storing a String into a HashSet, but sometimes objects of a custom type passed into a HashSet need to override the methods.

package Demo01; import java.util.ArrayList; import java.util.*; /** * @author Dell */ public class Test1 { public static void main(String[] args) { HashSet hashSet = new HashSet(); hashSet.add(new Student("2","zhang")); hashSet.add(new Student("8","name")); hashSet.add(new Student("4","jack")); hashSet.add(new Student("6","row")); hashSet.forEach(); } } class Student{ String id; String name; public Student(String id, String name) { this.id = id; this.name = name; } @Override public String toString(){ return id+" "+name; } @Override public int hashCode(){ return id.hashCode(); } @override public Boolean equals(Object Object){if(this == Object){return true; // Return true} if(! (object instanceof Student)){return false; // If not, return false} Student Student = (Student) object; Boolean b = this.id.equals(student.id); Return b; [2 zhang, 4 jack, 6 row, 8 name]Copy the code

TreeSet interface

TreeSet uses balanced binary trees to store elements. Such a structure ensures that there are no duplicate elements in TreeSet sets and they can be sorted. The compareTo () method, which is defined by Comparable, is called whenever elements in the collection are compared. The Comparable interface is not implemented when custom data is passed to TreeSet. To solve this problem, Java provides two methods: natural sort and custom sort.

// Sort package Demo01; import java.util.ArrayList; import java.util.*; /** * @author Dell */ public class Test1 { public static void main(String[] args) { TreeSet treeSet = new TreeSet(); treeSet.add(new Teacher("jack",18)); treeSet.add(new Teacher("rose",19)); treeSet.add(new Teacher("tom",19)); treeSet.add(new Teacher("rose",19)); System.out.println(treeSet); Class Teacher implements class Comparable{String name; int age; public Teacher(String name, int age) { this.name = name; this.age = age; } @Override public String toString(){ return name +":"+age; Override public int compareTo(Object obj){Teacher Teacher = (Teacher) obj; Name (this.age-teacher. age>0){return 1; } if(this.age- teacher.age==0){ return this.name.compareTo(teacher.name); } return -1; }} // The output is [Jack :18, Rose :19, Tom :19]Copy the code

The Teacher class implements the Comparable interface and overwrites the compareTo () method. In the compareTo () method, the age value is first modified, and -1 and 1 are returned based on the comparison result. When age is the same, name is compared. Teacher Teacher objects are first sorted by ascending age, by name if they are the same age, and the TreeSet collection removes duplicate elements.

// Customize the sort package Demo01; import java.util.*; /** * @author Dell */ public class Test1 { public static void main(String[] args) { // 1. TreeSet TreeSet = new TreeSet(new MyComparator()); treeSet.add("jack"); treeSet.add("hello"); treeSet.add("tom"); System.out.println(treeSet); TreeSet1 = new TreeSet((obj1,obj2)->{String s1 = (String) obj1; String s2 = (String) obj2; return s1.length() - s2.length(); }); treeSet1.add("jack"); treeSet1.add("tom"); treeSet1.add("hello"); System.out.println(treeSet1); } } class MyComparator implements Comparator{ @Override public int compare(Object obj1, String str1 = (String) obj1; String str2 = (String) obj2; int temp = str1.length()-str2.length(); return temp; }}Copy the code

The Map interface

Map Interface Overview

The Map interface is a two-column collection. Each element of the Map contains a Key object and a Value object. There is a mapping between the Key and the Value object. The key and value in a Map can be any data type, and the key object key cannot be repeated. When accessing elements in a Map, you can find the corresponding value as long as you specify a key.

A HashMap collection

A HashMap collection is an implementation class of the Map interface that stores key-value mappings. The keys and values of the collection are allowed to be empty, but the keys cannot be repeated, and the elements in the collection are unordered.

Map collection traversal

Iterator Iterator iterates through a Map collection

Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Iterator Because the Map elements are key-value pairs, there are two methods for Iterator traversal: keySet () and entrySet (). The keySet () method converts all the key objects in the Map to a Set. The Set of key objects is then converted into an Iterator interface object, and all the keys in the Map are iterated over and the corresponding values are retrieved based on the keys.

// This method is keySet() import java.util.*; /** * @author Dell */ public class Test1 { public static void main(String[] args) { Map map = new HashMap(); map.put("3", "Jack"); map.put("1", "Rock"); map.put("2", "Tom"); Set keySet = map.keySet(); Iterator = keyset.iterator (); Iterator = keyset.iterator (); While (iterator.hasnext ()) {Object key = map.keyset (); Object value = map.get(key); System.out.println(key + ":" + value); }}}Copy the code

The entrySet() method returns a Set of key-value pairs from the original Map as a whole, converts the Set containing the key-value pairs into an Iterator interface object, retrieves all of the key-value mappings in the Set, and retrieves the keys and values from the mappings.

// This method is the entrySet() method package Demo01; import java.util.*; /** * @author Dell */ public class Test1 { public static void main(String[] args) { Map map = new HashMap(); map.put("3", "Jack"); map.put("1", "Rock"); map.put("2", "Tom"); Set entrySet = map.entrySet(); Iterator iterator = entrySet.iterator(); While (iterator.hasnext ()){map.entry = (map.entry)(iterator.next()); // Get the Iterator while (iterator.hasnext ()){map.entry = (map.entry)(iterator.next()); Object key = entry.getKey(); Object value = entry.getValue(); Println (key + ":" + value); system.out.println (key + ":" + value); }}}Copy the code

Use the forEach method to traverse the Map collection

public class Test1 { public static void main(String[] args) { Map map = new HashMap(); map.put("3", "Jack"); map.put("1", "Rock"); map.put("2", "Tom"); map.forEach((key, value) -> System.out.println(key + ":" + value)); }}Copy the code

The map Collection also provides a values () method that directly retrieves a Collection of all the values in the map

public class Test1 { public static void main(String[] args) { Map map = new HashMap(); map.put("3", "Jack"); map.put("1", "Rock"); map.put("2", "Tom"); Collection values = map.values(); ForEach (v-> system.out.println (v)); }}Copy the code

Use the LinkedHashMap collection to ensure the order in which elements are added

Create the LinkedHashMap collection to ensure that the access order is consistent.

The Properties collection

The Properties collection, a subclass of HashTable, is used to store strings of keys and values. Test.properties = test.properties = test.properties

Background = black
name = zhang 
age = 19

Copy the code
package Demo01; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; public class Test1 { public static void main(String[] args) throws Exception { // 1. Properties = new properties (); // Load the file test.properties PPS. Load (new FileInputStream("test.properties")); ForEach ((k,v)-> system.out.println (k +":"+ v)); FileOutputStream out = new FileOutputStream("test.properties"); // Add ps.setProperty("charset"," utF-8 ") to the properties class; // Write the new key-value pair information in the properties collection to the configuration file PPS. Store (out," new charset code "); }} // The first output is background:black name: Zhang age:19 // the second output is charset:UTF-8 background:black name: Zhang age:19Copy the code

The last

At the end of the article the author sorted out a lot of information for you! Including Java core knowledge + a full set of architect learning materials and video + first-line factory interview treasure dictionary + resume template interview ali Meituannetease Tencent Xiaomi IQiyi Quick hand bilibili bilibili interview questions +Spring source code collection +Java architecture actual combat e-books and so on! Friends in need of attention to the public number: a bright future, can download their own!