Java Collection Knowledge Points Overview and Code Interpretation

Posted by a2bardeals on Sat, 18 May 2019 23:17:39 +0200

Collection (List And Set)

1. In practical development, it is necessary to store the objects used in specific data structure containers. JDK provides such a container-collection.

2.Collection is an interface whose sub-interfaces are List and Set

3. The difference between List and Set: List is an ordered repeatable set (which can store repeatable elements) and Set is an unordered non-repeatable set (which cannot store repeatable elements). Whether an element repeats depends on the results of the equals () comparison of the elements.

Reference to Collection Holding Objects

Collections store reference type elements, and collections only store references to each element, rather than storing elements themselves into collections. Basic type data is automatically boxed as Integer type data.

Common methods in Collection

add() method

1.Collection defines an add method to add new elements to the collection

		- Boolean add (E) E represents data types
 This method adds a given element to the collection and returns true if it succeeds or false if it does not.

The demo code is as follows:

public void testAdd() {
	Collection<String> c = new ArrayList<String>();
	System.out.println(c);//[]
	c.add("a");
	c.add("b");
	c.add("c");
	System.out.println(c);//[a,b,c]
}

contains() method

	-boolean contains(Object o)
This method is used to determine whether a given element is included in the set, if it is included, it returns true, otherwise it returns false.
Note: Sets determine whether elements are included in a set based on the equals method.
Generally, it is necessary for classes to rewrite equals methods to ensure the reasonableness of comparisons.

The demo code is as follows:

public void  testContains() {
	Collection<Person> persons = new ArrayList<Person>();
	persons.add(new Person("Zhang San",20));
	persons.add(new Person("Li Si",21));
	persons.add(new Person("Wang Wu",22));
	persons.add(new Person("Zhao Liu",23));
	Person p =new Person("Li Si",21);
	//List set contains method is related to object equals method
	boolean flag = persons.contains(p);
	//If the Person class does not override equals, the method will be false
	System.out.println(flag);//true
}

int size(),void clear,boolean isEmpty

- int size() returns the total number of elements in the current collection
 - void clear() method clears the current collection
 - boolean isEmpty() method is used to determine whether the set is empty

The demo code is as follows:

public void testSizeAndClearAndIsEmpty() {
	Collection<String> c = new HashSet<String>();
	System.out.println(c.isEmpty());//true
	c.add("Java");
	c.add("C");
	c.add("php");
	c.add("C#");
	c.add("Java");
	System.out.println(c);//Unordered and unrepeatable: [C#, Java, C, php]
	System.out.println("isEmpty:"+c.isEmpty()+",size:"+c.size());//false  4
	c.clear();
	System.out.println("isEmpty:"+c.isEmpty()+",size:"+c.size());//true 0
}

addAll() method and containsAll() method

	-boolean addAll(Collection<? extends E> c)
This method requires us to pass in a collection and add all elements in that collection to the current collection.
If the collection changes due to calls, return true
	-boolean containsAll(Collection<?> c)
This method is used to determine whether the current set contains all elements in a given set.
Returns true if included

The demo code is as follows:

public void testAddAllAndContainsAll() {
	Collection <String >c1 = new ArrayList<String>();
	c1.add("java");
	c1.add("c");
	c1.add("php");
	c1.add("c#");
	c1.add("js");
	System.out.println(c1);//java c php c# js
	Collection <String> c2 = new HashSet<String>();
	c2.addAll(c1);
	System.out.println(c2);//Disordered java php c js c#
	Collection <String>c3= new ArrayList<String>();
	c3.add("java");
	c3.add("c");
	System.out.println(c1.containsAll(c3));//true
}
}

Iterator

Iterators are used to traverse collection elements and obtain iterators using methods defined by Collection:

Iterator <E> it = Collection name.iterator();

An iterator is an interface, and the set provides an iterator implementation by using internal classes when rewriting Collection's iterator() method.

Iterator provides a unified way to traverse a set. It provides two ways to traverse a set:

boolean hasNext(): Determines whether there are elements in the collection that can be traversed
 E next(): Returns the next element of the iteration

The demo code is as follows:

public void testHashNextAndNext() {
	Collection<String> c = new HashSet<String> ();
	c.add("java");
	c.add("c");
	c.add("c#");
	c.add("php");
	c.add("python");
	//Obtain iterators
	Iterator<String> it = c.iterator();
	//Determine whether there are elements and traverse them
	while(it.hasNext()) {
		//Return element
		String s = it.next();
		System.out.println(s);
	}
}

remove() method

When iterators are used to traverse a collection, elements in the collection cannot be deleted by the remove() of the collection, otherwise exceptions will be thrown and changed concurrently.

void remove()
1. We usually use the remove() method provided by the iterator itself to delete the elements iterated through the next() method.
2. The method of deleting iterators is to delete elements in the original set.
3. It is important to note that elements that must be iterated through the next method of the iterator before calling the remove method.
That's the element that's deleted, and you can't call the remove method again unless you call the next method again
 Can call remove() method

The demo code is as follows:

public void testRemove() {
	Collection<String> c = new HashSet<String>();
	c.add("java");
	c.add("C");
	c.add("C#");
	c.add("PHP");
	c.add("python");
	System.out.println(c);
	Iterator<String> it = c.iterator();
	while(it.hasNext()) {
		String s = it.next();
		if(s.indexOf("C")!= -1) {  //Not equal to - 1 is to find equal to - 1 is not to find
			it.remove();//Delete elements containing the letter C
		}
	}
	System.out.println(c);//python java php deletes all elements containing the letter C
}

Enhanced for cycle

After version 5.0 of java, a new feature was introduced to enhance for loops, also known as new loops, which, unlike traditional loops, are only used to traverse arrays and collections.

Syntax:

for (element type e: set or array){
	Circulatory body;
}
The new loop is not a new syntax, but in the compilation process, the compiler transforms the new loop into an iterator pattern.
So it can be said that the essence of the new cycle is iterator.

The demo code is as follows:

	public void testFor() {
		Collection<String> c = new HashSet<String>();
		c.add("java");
		c.add("c");
		c.add("php");
		c.add("c#");
		c.add("python");
		for (String string : c) {
			System.out.println(string.toUpperCase()+" ");
			//C# PYTHON JAVA C PHP
		}
}

Generic mechanism

1. Generic mechanism is a feature introduced by JavaSE 5.0. The essence of generics is parameterized type. In the process of defining class interfaces and methods, the data types operated are specified by the parameters passed in.

2.Java generic mechanism is widely used in the collection framework. All collection types have generic parameters, so that when creating a collection, you can specify the type of elements placed in the collection, and the java compiler can check according to this type, which can reduce the possibility of code errors at run time.

3. In the definition of the ArrayList class, E is a generic parameter. When creating an object, the type can be passed as a parameter. At this time, all E defined by the class will be replaced by the incoming parameter.

The demo code is as follows:

public void testE() {
	ArrayList<String> list = new ArrayList<String>();
	list.add("One");//Only String-type data can be added
}

Set Operations-Linear Tables

List

1.List interface is a sub-interface of Collection, which is used to define linear table data structure. List can be understood as an array of objects, but the number of elements can be dynamically increased or decreased.

2. The two common implementation classes of List interface are ArrayList and LinkedList, which implement List interface in the way of dynamic array and linked list respectively.

3. ArrayList and LinkedList are logically identical, but they differ in performance. ArrayList is more suitable for random access and LinkedList is more suitable for insertion and deletion.

common method

List not only inherits the method defined by Collection, but also defines a series of methods according to the data structure of its linear table. The most common methods are subscript-based get and set methods.

E get(int index) gets the element corresponding to the specified subscript in the collection, which starts at 0
 E set(int index,E element) stores the specified element in the specified location and returns the in-situ element

The demo code is as follows:

public void testGetAndSet() {
	List<String> list = new ArrayList <String>();
	list.add("java");
	list.add("c++");
	list.add("php");
	list.add("python");
	list.add("c#");
	//The get method traverses List
	for (int i = 0; i < list.size(); i++) {
		System.out.println(list.get(i).toUpperCase());
		//JAVA C++ PHP PYTHON C#
	}
	String value = list.set(1, "hadoop");
	System.out.println(value);//c++
	System.out.println(list);//java hadoop php python c#
	//Get hadoop, insert Hadoop into index 3, return python, and then insert Python into index 1
	list.set(1, list.set(3, list.get(1)));
	System.out.println(list);
	//java python php hadoop c#
}

Insert and delete according to subscript operation

void add(int index,E element) inserts a given element into a specified location, in situ, and subsequently
 Elements move backwards in order
 E remove(int index): Delete the element at a given location and return the deleted element

The demo code is as follows:

public void testInsertAndRemove() {
	List<String> list = new ArrayList<String>();
	list.add("java");
	list.add("c++");
	System.out.println(list);//java c++
	
	list.add(1,"cpp");
	System.out.println(list);//java cpp c++
	
	String a = list.remove(2);
	System.out.println(list+".."+a);//java cpp...c++
}

Get a sublist

Note that the List obtained by sublist occupies the same storage space as the original List, and the operation of the sublist will affect the original List.
List < E > sublist (int from index, int to index) from index and to index are interceptors
 List's first and last subscriptions, not before and after the package.

The demo code is as follows:

public void testSubList() {
	List<Integer> list = new ArrayList<Integer>();
	for (int i = 0; i < 10; i++) {
		list.add(i);
	}
	System.out.println(list);//0-9
	
	List<Integer> sublist = list.subList(3, 8);//3 4 5 6 7
	//The List obtained by subList and the source List share the same resources
	for (int i = 0; i < sublist.size(); i++) {
		sublist.set(i, sublist.get(i)*10);
	}
	System.out.println(sublist);//30 40 50 60 70
	//The same storage space is used to affect the original List for sub-List operations
	System.out.println(list);// 0 1 2 30 40 50 60 70 8 9
	//Note that clear can only delete contiguous elements
	list.subList(3, 8).clear();
	System.out.println(list);// 0 1 2  8 9
}

Conversion between List and Array

1.List's toArray method is used to convert collections into arrays, but in fact this method is defined in the collection interface, so all collections have this function.

Object[] toArray()
<T> T[] toArray(T[] a)
The second method is more commonly used. We can pass in an array of the specified type, the element type of the array.
Agreement. The return value is a converted array that retains all elements in the collection

The demo code is as follows:

public void testToArray() {
	List<String> list = new ArrayList<String>();
	list.add("a");
	list.add("b");
	list.add("c");
	String [] strArr = list.toArray(new String[] {});
	System.out.println(Arrays.toString(strArr));//[a,b,c]
}

2. A static method asList is provided in the Arrays array class. Using this method, we can convert an array into a corresponding List set.

static <T> List<T> asList<T...a>
The element type of the returned List collection is determined by the element type of the incoming array.
We cannot add or delete elements to the returned collection, otherwise we will throw an exception and modify the elements of the collection.
It affects the elements corresponding to the array.

The demo code is as follows:

public void testArrayToList() {
	String [] strArr = {"a","b","c"};
	List<String> list = Arrays.asList(strArr);
	System.out.println(list);
	//list.add("d"); // throw an exception
	//System.out.println(list);
	List<String> list1 = new ArrayList<String>();
	list1.addAll(Arrays.asList(strArr));
	list1.add("d");
	System.out.println(list1);
	/*
	 * Converting an array to a List is not possible to add or delete. If you need to add or delete, you can use the empty set to call addAll method to add all new sets to the transformed set.
	 * 	It's ready for operation.
	 */
}

List sorting

1.Collections is a tool class of collections. It provides many methods for us to manipulate collections. Among them, the sort method is used to sort collections.

The method is defined as:
-void sort(List<T> list)
The function of this method is to sort the given set elements naturally.

The demo code is as follows:

	public void testSort() {
	List<Integer> list = new ArrayList<Integer>();
	Random r = new Random();
	for (int i = 0; i <10;i++) {
		list.add(r.nextInt(100));
	}
	System.out.println(list);//[7, 77, 94, 15, 6, 83, 35, 30, 24, 49]
	Collections.sort(list);//Ranking from small to large
	System.out.println(list);//[6, 7, 15, 24, 30, 35, 49, 77, 83, 94]
}

Comparable

Collections'sort method is to sort the collection naturally, so there must be a division of size between two element objects. How to judge the division of size? In fact, collection elements sorted using Collections must be implementation classes of the Comparable interface.

This interface represents that subclasses are comparable because implementing interfaces must override abstract methods

int compareTo(T t);
This method is used to compare the current object with the given object.
If the current object is greater than an integer whose return value is greater than 0 for a given object
 Returns an integer with a value less than 0 if the current object is less than the given object
Returns 0 if two objects are equal

The demo code is as follows:

public void testComparable() {
	/*
	 * Cell Implementation of Comparable interface
	 * compareTo The method logic is to sort by the size of the x value
	 */
	List<Cell> cells = new ArrayList<Cell>();
	cells.add(new Cell(2,3));
	cells.add(new Cell(5,1));
	cells.add(new Cell(3,2));
	Collections.sort(cells);
	System.out.println(cells);
	////2,3   3,2   5,1
}

Comparator

1. Once the Java class implements the Comparable interface, its comparison logic has been determined. If you want to temporarily specify the comparison rules in the sorting operation, you can use the Comparator interface callback mode.
2. The Comparator interface requires the implementation class to override its defined methods:

int compare(T o1,T o2)
If the return value of O1 > O2 method should be greater than 0
 If the return value of O1 < O2 method should be less than 0
 If o1=o2, return 0

The demo code is as follows:

	public void testComparator() {
	List<Cell> cells = new ArrayList<Cell>();
	cells.add(new Cell(2,3));
	cells.add(new Cell(5,1));
	cells.add(new Cell(3,2));
	//Temporarily sort this.y-o.y by Y
	Collections.sort(cells, new Comparator<Cell>() {
		@Override
		public int compare(Cell o1, Cell o2) {
			// TODO Auto-generated method stub
			return o1.y-o2.y;
		}
	});
	System.out.println(cells);//5,1 3,2 2,3
	//Temporary callback
	Collections.sort(cells);
	System.out.println(cells);//2,3 3,2 5,1
}

Comparison and conclusion

1. Practical Collection.sort() for collections

2. For object comparison in a collection, we need to specify the comparison logic, implement the Comparable interface and rewrite the custom logic of the compareTo method.

3. To change the comparison rules temporarily, we need to use Collections.sort(List,Comparator) to rewrite the comparison method custom logic of Comparator interface by callback.

Queue and Deque

Queue

1. Queue is a commonly used data structure. Queues can be regarded as special linear tables. Queues restrict access to linear tables. Queues can only add elements from one end of the linear table and extract elements from the other end.

2. Queues follow the first-in-first-out principle

3.JDK provides Queue interface, and makes LinkedList implement it. The reason why LinkedList implements Queue interface is that Queue often needs to add and delete operations, and LinkedList is more efficient in this respect.

4. The main methods of Queue interface are as follows:

Boolean offer (E): Add an object to the end of the queue and return true if the addition is successful
 E poll(): Delete and return an element from the head of the team
 E peek(): Returns the head element but does not delete it

Demonstrate the following code:

public void testQueue() {
	Queue<String> queue = new LinkedList<String>();
	queue.add("a");
	queue.offer("b");
	queue.offer("c");
	System.out.println(queue);//a b c
	String str = queue.peek();
	System.out.println(str);//a
	String str1 = queue.poll();
	System.out.println(str1);//a
	System.out.println(queue);//b c
	
	while(!queue.isEmpty()) {
		str = queue.poll();
		//Traversal can only be done by deleting the first poll method. After deleting the first poll element, it will become the second one, while peek will not change the first poll element.
		System.out.println(str+" ");//b c
	}
}

Deque

1.Deque is a subinterface of Queue, which defines the so-called bidirectional queue. That is, from both ends of the queue can be offered and polled respectively. LinkedList implements this interface

2. If Deque is limited to only entering and leaving the queue from one end, the stack Stack data interface can be implemented.
Input is called push and out is called pop.

3. The stack follows the principle of "first in, last out"

public void testStack() {
	Deque<String> stack = new LinkedList<String>();
	stack.push("a");
	stack.push("b");
	stack.push("c");
	System.out.println(stack);//c b a
	String s = stack.peek();
	System.out.println(s);//c
	while(!stack.isEmpty()) {
		 s = stack.pop();
		 System.out.println(s+" ");// c  b  a
	}
	System.out.println(stack);//[]
}
}

Map interface

1. The set defined by the Map interface, also known as lookup tables, is used to store so-called "Key-Value" mapping pairs. Key can be regarded as an index of Value, and objects as keys can not be duplicated in a collection.

2. According to the different internal data structure, there are many implementation classes of Map interface, among which HashMap implemented internally for hash table and TreeMap implemented internally for sorting binary tree are commonly used.

put() method

1.Map interface defines put method to store elements in Map

V put(K key,V value)

2. Store the key-value pair in Map. If the key has been included in the collection, the operation will replace the corresponding value of the key, the return value is the original corresponding value of the key, and if the key is not included, null will be returned.
The demo code is as follows:

//Create member variables
Map<String,Person> persons = new HashMap<String,Person>();
@Before //Represents that before is executed every time a test is executed
public void testPut() {
	persons.put("Zhang San", new Person("Zhang San",80));
	persons.put("Yan Wei", new Person("Yan Wei",81));
	//System.out.println(persons);
}

3.Map interface defines get method to get elements from Map

V get(Object key) returns the value object corresponding to the parameter key, and null if it does not exist

The demo code is as follows:

@Test
public void testGet() {
	Person  p = persons.get("Zhang San");
	System.out.println(p);//Person [name = Zhang San, age=80]
}

containsKey() method

The Map interface defines whether a key exists in the Map or not.

boolean containsKey(Object key)
Returns true if the Map contains a given key

The demo code is as follows:

@Test
public void testContainsKey() {
	System.out.println(persons.containsKey("Yan Wei"));//true
}

hashCode method

1. From the principle of hashMap, we can see that the return value of the hashCode() method of key plays a role in storing elements in HashMap.
Very important, and the hashCode() method is actually defined in Object

2. For objects that rewrite equals methods, it is generally necessary to rewrite hashCode methods inherited from Object classes appropriately.
(The hashCode method provided by Object returns the integer form of the memory address of the object)

3. Rewriting hashCode method should pay attention to two points:

 		- Consistency with the equals method, that is, the hashCode method returns the same value when comparing the two objects returning true with equals
 		- The value returned by hashCode should meet the requirements of hash algorithm. If many objects have the same hashCode return value, it will be greatly reduced.
  			Efficiency of hash tables, usually using tools provided by IDE eclipse to automatically generate hashCode methods

Loading factor and hashMap optimization

1.Capacity: Capacity. The number of bucket s in the hash table is the hash array size.

2.Inintal capacity: Initial capacity. When creating hash tables, the number of initial bucket s is 16 by default.
Specific capacity can also be used

3.Size: Size, the number of data stored in the current hash table

4.Load factor: The default value of load factor is 0.75. When adding data to the hash table, if the size/capacity value is greater than factor, the capacity will be expanded.
And rehash

5. Performance optimization: When the loading factor is small, the hash lookup performance will be improved, and the capacity of the hash bucket will be wasted. 0.75 is the result of relative balance of performance and space
Specify reasonable capacity when creating hash tables to reduce rehash and improve performance

Map traversal

1.Map provides three ways to traverse

Traverse all key s
 Traversing through all key-value pairs
 Traveling through all value s -- not often used

2. The method of traversing all key s

Set<K> keySet()
This method returns all keys stored in the current Map to a Set collection

The demo code is as follows:

@Test
public void testKeySet() {
	Set<String> keyset = persons.keySet();
	System.out.println(keyset);//[Zhang San, Yan Wei]
	for (String string : keyset) {
		System.out.println("key:"+string);
		/*
		 * key:Zhang San
		 * key:Yan Wei
		 */
	}
}

entrySet() method traverses all key-value pairs

Set<Entry<k,v>> entrySet()
This method encapsulates each set of key-value pairs in the current Map as an Entry object and stores them in one
 Set Collection Return

The demo code is as follows:

public void testEntrySet() {
	Set<Entry<String,Person>> entrySet = persons.entrySet();
	//[Zhang San = Person [name = Zhang San, age=80], Yan Wei = Person [name = Yan Wei, age=81]]
	System.out.println(entrySet);
	
	for (Entry<String, Person> entry : entrySet) {
		System.out.println(entry.getKey()+":"+entry.getValue());
		/*
		 * Zhang San: Person [name = Zhang San, age=80]
		 * Yan Wei: Person [name = Yan Wei, age=81]
		 */
	}
}

Ordered Map

1. Hash table and linked list implementations using Map interface have predictable iteration order. This implementation differs from HashMap in that:
LinkedHashMap maintains a two-way circular list that defines the order of iteration, which is usually the order in which elements are stored.

2. It is important to note that if you re-store an existing Key in a Map, the key location will not change, and the value value value will change.

The demo code is as follows:

@Test
public void testLinkedHashMap() {
	LinkedHashMap<String,Person> map = new LinkedHashMap<String,Person>();
	map.put("Lee Chi Ho", new Person("Lee Chi Ho",99));
	map.put("Li Si", new Person("Li Si",18));
	System.out.println(map);
	//{Li Zhihao = Person [name = Li Zhihao, age=99], Li Si = Person [name = Li Si, age=18]}
	map.put("Li Si", new Person("Li Si",66));
	System.out.println(map);
	//{Li Zhihao = Person [name = Li Zhihao, age=99], Li Si = Person [name = Li Si, age=66]}
}

Topics: Java PHP Python Hadoop