Java object-oriented (9): collection

set

Introduction
• We have studied arrays before. Arrays are a structure that can store multiple data (objects), but arrays have certain limitations.
– The characteristics of the array in memory storage:
• After the array is initialized, the length is determined.
• The type of the array declaration determines the type of element initialization-
the disadvantages of the array in storing data:
• After the array is initialized, the length is immutable and it is not easy to expand.
• There are few attributes and methods provided in the array, which is inconvenient Perform operations such as adding, deleting, and inserting, and the efficiency is not high. At the same time, the number of storage elements cannot be directly obtained
. The data stored in the array is ordered and can be repeated. -
• The characteristics of the stored data are single.
• Java collection classes can be used to store multiple objects of varying numbers, and can also be used to store associative arrays with mapping relationships.

What is a collection?
A collection is also called a container, which is a container that holds a group of objects. For example: customer list, order list
Learn the general idea of ​​the collection framework
• how to add elements
• how to obtain elements
• how to delete elements
• how to traverse elements

Collection frame icon

Insert picture description here
Insert picture description here

• Commonly used interfaces in collections
-Collection interface
• Collection interface definition standards
-List
• Inherit the Collection interface, the stored data objects are ordered and repeatable
-Set
• Inherit the Collection interface, the stored data objects are disorderly and not repeated
-Map
• Is a composition The key-value object of the pair, that is, it holds a key-value pair. There can be no duplicate keys in the map

Collection interface

Insert picture description here

Iterator interface

 Iterator object is called iterator (a kind of design pattern), which is mainly used to traverse the elements in the Collection.

 The iterator pattern is defined to provide a way to access each element in a container object without exposing the internal details of the object. The iterator pattern is born for containers. Similar to "the conductor on the bus," "the flight attendant on the train," and "the flight attendant."

 The Collection interface inherits the java.lang.lterable interface, which has an iterator() method, so all collection classes that implement the Collection interface have an iterator() method to return an object that implements the Iterator interface.

 Iterator is only used to traverse the collection. Iterator itself does not provide the ability to hold objects. If you need to create an iterator object, you must have a collection to be iterated.

 The collection object gets a brand new iterator object every time it calls the iterator() method, and the default cursor is before the first element of the collection.
Insert picture description here

Iterator interface

 boolean hasNext()
 Object next()
 void remove()
Note :
Iterator itself is not a collection, and will not generate a copy of the collection. The iterator traverses the collection itself.
When the iterator is iterating the elements, if you want to delete the element, you need to use the remove() method of the iterator, and you cannot use the remove() method that comes with the Collection.

To enhance for , the internal implementation is still implemented using iterators. (If you want to find out if it is really an iterator, you can decompile the compiled .class file yourself, and then check the source code, you will find that the enhanced for is implemented using an iterator)
 Small exercise for enhancing the for: the following code What is the output?
Insert picture description here

Operation result:
haha
haha
haha

 Enhanced for exercises:
Insert picture description here

Operation result:
ha
ha
ha ha ha ha

Override the equals and hashCode methods. For
example, when the elements added to the collection are objects of the class written by yourself, we need to override the equals and hashCode methods when we want to distinguish whether they are the same element through custom attributes. The overriding method can be directly Use the automatic generation of the editor. (If you don’t understand, please click here )

List interface

– Features
• Inherit Collection, allow repetition, place elements in the order of element placement without rearranging them.
 Three main classes: ArrayList, LinkedList, Vector comparison,
 ArrayList bottom layer is an array structure, fast query, slow addition and deletion, Threads are not safe and efficient.
 The bottom layer of LinkedList is a linked list data structure, which is slow in query, fast in addition and deletion, unsafe threads, and high efficiency.
 The bottom layer of Vector is an array structure, with fast query, slow addition and deletion, thread safety, and low efficiency.
Insert picture description here
Analysis:
ArrayList array implementation, (storage address is continuous) to implement the List interface, is actually a dynamic variable array implementation (Object [] E), can be expanded, the principle of expansion is to increase by 50%
-before JDK1.7, initialize An array of 10 elements is created directly.-
After JDK1.8, an empty array is created during initialization. When saving data for the first time, an array of 10 elements is created. In
actual development, if you can roughly know The number of elements can be directly given an initial value through the constructor: public ArrayList(int initialCapacity), which can reduce the number of expansions and improve efficiency.

Linked list implementation of linkedList (that is, linked list, or doubly linked list, the storage address is not continuous)

Vector , is a reassignable Object (dynamic) array.
Like ArrayList, except that the methods have the synchronized keyword, they are all synchronized methods and are thread-safe.
ArrayList is thread-unsafe. In actual development, it is recommended to use thread-unsafety and high execution efficiency; thread-safety issues should be left to the application to control, rather than complete with tool classes. Vector is rarely used in development.

Collections class

• The java.util.Collections class provides some static methods to implement some common algorithms based on the List container
– void sort(List) sorts the elements in the List container
– void shuffle(List) random sort
– void reverse(List) reverse
– Void fill(List,Object) rewrite the entire List container with a specific object

@Test
	public void testCollections1() {
    
    
		List list=new ArrayList();
		
		list.add("D");
		list.add("F");
		list.add("A");
		list.add("J");
		list.add("B");
		
		//排序
		Collections.sort(list);
		System.out.println(list);
		
		//反转
		Collections.reverse(list);
		System.out.println(list);
		
		//随机排序
		Collections.shuffle(list);
		System.out.println(list);
		//填充
		Collections.fill(list, "000");
		System.out.println(list);
	}

Comparable interface

•? The previous algorithm determines the "size" of the object according to what
• All sortable classes implement the java.lang.Comparable interface, this interface has only one method:
– public int compareTo(Object obj)
• If you need to compare objects created by yourself, You need to define a sorting rule for this class, you need to implement the Comparable interface, override the compareTo() method, and define the sorting rule.
• Such as:
public int compareTo(Object o){ Person p = (Person)o; return pname.compareTo(p.pname); }


List Interview Questions
• Interview Questions: What content will be output?
Insert picture description here

Operation result:
1
2

Set interface

Set interface characteristics
-inherit Collection, but do not allow repetition, disorder.
– The Set interface does not introduce new methods, so Set is a Collection, but its behavior is different.

HashSet : As the main implementation class of the Set interface; it is not thread-safe and can store null values.
• HashSet bottom layer: the structure of array + linked list.
The bottom layer is also an array, with an initial capacity of 16. When the usage rate exceeds 0.75, (16*0.75=12) will expand the capacity to twice the original capacity. (16 expansion is 32, followed by 64, 128, ... etc.)

LinkedHashSet : As a subclass of HashSet; when traversing its internal data, it can be traversed in the order of addition. You can guarantee that you can withdraw it as you deposit it.

TreeSet : You can sort according to the specified attributes of the added objects.

 The process of adding elements to the Set interface: Take HashSet as an example: we add element a to HashSet,
 First call the hashCode() method of element a to calculate the hash value of element a, and this hash value is calculated by a certain algorithm The output element should be stored in the storage position of the underlying array of HashSet (ie: index position), and determine whether there is an element at this position in the array:
– If there is no other element at this position, the element a is added successfully.
– If there are other elements b (or multiple elements in the form of a linked list) at this position, compare the hash values ​​of element a and element b:
• If the hash values ​​are not the same, then element a is added successfully (added to At this position).
• If the hash values ​​are the same, you need to call the equals() method of the class where element a is located
– equals(). Returns true, and element a fails to be added
– equals() returns false, then element a is added successfully.

Intersection union

		Set s1 = new HashSet();
		s1.add("a");s1.add("b");s1.add("c");
		Set s2 = new HashSet();
		s2.add("a");s2.add("b");s2.add("f");
		Set sn = new HashSet(s1);
		//并集
		sn.addAll(s2);
		System.out.println(sn);
		Set su = new HashSet(s1);
		//交集
		su.retainAll(s2);
		System.out.println(su);

TreeSet class:

 The elements to be added must be of the same class object. In other words, elements of different types of objects cannot be added. And the objects are comparable.

 The elements of TreeSet support 2 sorting methods: natural sorting or sorting according to the provided Comparator.

 Pay special attention to one point: TreeSet judges whether two objects are equal, not according to the equals method; it is judged according to the compareTo method, which means that the two objects compareTo returns 0, indicating that the two objects are equal, so they will not be added. The second object. (The same object will not be added repeatedly)

 TreeSet sorting method: natural sorting

@Test
	public void testHashSet() {
    
    
		Set set1=new HashSet();
	
		set1.add("g");
		set1.add("d");
		set1.add("a");
		set1.add("f");
		
		System.out.println(set1);// [a, d, f, g]
	}

 TreeSet sorting method: custom sorting.
Insert picture description here
Insert picture description here

Set Interview Question 1
How to remove duplicate elements in the List collection? What is the output of
Insert picture description here
Set Interview Question 2
?
Insert picture description here

运行结果:
[Person [id=1002, name=BB], Person [id=1001, name=AA]]
[Person [id=1002, name=BB], Person [id=1001, name=CC]]
[Person [id=1002, name=BB], Person [id=1001, name=CC], Person [id=1001, name=CC]]
[Person [id=1002, name=BB], Person [id=1001, name=CC], Person [id=1001, name=CC], Person [id=1001, name=AA]]

Map interface

Map interface features
-Map provides a mapping relationship, in which the elements are stored in the form of key-value pairs, which can quickly find the value based on the key.
– The key-value pairs in the Map exist in the form of object instances of the Entry type.
– The key (key value) cannot be repeated, the value value can be repeated, one value value can form a corresponding relationship with many key values, and each key can only be mapped to one value at most.
– Map supports generics, in the form of Map<K,V>.
-Use the put (K key, V value) method to add in the Map.

Map interface class diagram structure
Insert picture description here
-main methods
Insert picture description here
• Map main implementation class
Insert picture description here
Insert picture description here
HashMap : It is the main implementation class of Map. This class is usually used in development. Threads are not safe and efficient. Can store null values ​​(key-value can be null).

LinkedHashMap is a subclass of HashMap. It uses a linked list method to ensure the order of elements, that is, how to store and retrieve them. The principle is to add a pair of pointers to the original HashMap to save the pointers of the previous element and the next element. When traversing elements frequently, the efficiency is relatively high, you can consider using this class.

Hashtable : ancient implementation class, thread-safe, low efficiency. (Null value cannot be stored, neither key nor value can be null)

• The Properties class, a subclass of the Hashtable class, is commonly used to process configuration files. Both key and value are of String type

TreeMap : It is guaranteed to sort according to the added key-value to realize sorting traversal. At this time, consider the natural ordering or custom ordering of keys.

The bottom layer of HashMap :
• Array + linked list (jdk7 and before)
• Array + linked list + red-black tree (jdk 8)

• Description of the underlying storage of the
Map : Understanding of the Map structure:
– Keys in the Map: unordered and non-repeatable. Use set to store all keys.
– Value in Map: Unordered and repeatable. Use Collection to store all values.
– A key-value pair key-value constitutes an Entry object.
– Entry in Map: Unordered and non-repeatable. Use Set to store all entries.

 Description of the underlying storage process of Map:
– The underlying implementation principle of HashMap: (take jdk7 as an example)
– HashMap map = new HashMap(): After instantiation, the bottom layer creates an array Entry[] table with a length of 16. When calling put(key1, value1) of the map class:
– First, call the hashCode() of the class where key1 is located to calculate the key1 hash value. After this hash value is calculated by a certain algorithm, the storage location in the Entry array is obtained. If the data at this position is empty, the key1-value1 at this time is added successfully.
– If the data at this location is not empty, (meaning that there are one or more data (in the form of a linked list) at this location), compare the hash value of key1 with one or more data that already exists: if key1 is The hash value is different from the hash value of the existing data. At this time, key1-value1 is added successfully.
– If the hash value of key1 is the same as the hash value of an existing data (key2-value2), continue to compare: call equals(key2) of the class where key1 is located. If equals() returns false: add key1-vaLue1 at this time success.
– If equals() returns true: replace value2 with value1.
– The default expansion method: expand the capacity to twice the original capacity, and copy the original data.

 Compared with jdk7, jdk8 is different in the bottom layer implementation:
 1.new HashMap(): The bottom layer does not create an array of length 16.
 2. The bottom array of jdk8 is: Node[], not Entry[].
 3. When the put() method is called for the first time, an array of length 16 is created at the bottom layer.
 4. The underlying structure of jdk7 is only: array + linked list.
The underlying structure in jdk8: array + linked list + red-black tree.
Map demo

		Map m = new HashMap();
		m.put("1001",new Person("333","张三"));
		m.put("1002",new Person("444","李四"));
		m.put("1003",new Person("555","王五"));
		//System.out.println(m.get("1002"));
		//m.put("1001",new Person("200333","张三"));
		Set s = m.keySet();
		
		Iterator it = s.iterator();
		while(it.hasNext()){
    
    
			System.out.println(it.next());
		}

 LinkedHashMap presentation: an orderly presentation

Insert picture description here
 Demonstration of TreeMap: Demonstration of natural sorting method

Insert picture description here
 Demonstration of TreeMap: Demonstration of custom sorting mode Demonstration
Insert picture description here
of Properties class
Insert picture description here

to sum up

Data structure
ArrayXxx: The underlying data structure is an array, the query is fast, and the addition and deletion is slow.
LinkedXxx: The underlying data structure is a linked list, and the query is slow, and the addition and deletion is fast.
HashXxx: The underlying data structure is a hash table. Rely on two methods: hashCode() and equals()
TreeXxx: The underlying data structure is a binary tree. Two ways of sorting: natural sorting and comparator sorting

buibuib ...

Continue studying…

Guess you like

Origin blog.csdn.net/zhangzhanbin/article/details/112203723