aggregate

Time:2022-5-27

aggregate

1: Set concept

Object, which implements common operations on objects, similar to array functions

2: Differences between sets and arrays:

  1. The length of array is fixed, and the length of set query is not fixed

  2. Arrays can store basic and reference types, while collections can only store reference types

Location: java Util*

Collection system collection

image-20220310180206702

Features: it represents a group of objects of any type. It is unordered, has no subscript, and cannot be repeated

method:image-20220310181010939

method:

add( ), remove( ),contains( ),isEmpty( )

Collection is an abstract class and cannot be new directly,

Collection collection = new arraylist(); // when traversing elements, because the object has no subscript //1, enhance for (object object: Collection) {student student = (student) object; system.out.println (student.tostring()); } // 2, using iterator iterator = collection Iterator(); While (iterator.hasnext()) {student student1 = (student) iterator.next(); system.out.println (student1.tostring()); }

ArrayList

ArrayList uses:

//Create a set ArrayList al = new arraylist(); //1, add student S1 = new student ("Xiaoming", 12); Al.add (S1); //2, delete al.remove (new student ("Xiaoming", 12))// The equals() method //3 will be called to iterate over (key) //for loop for (int i = 0; I < al.size(); I++) {system.out.println (al.get (I)); } // enhanced for (object object: Al) {system.out.println (object); } // use the iterator iterator it = al.iterator(); While (it.hasnext()) {system.out.println (it.next()); } // use the list iterator (you can traverse backwards or forwards) listiterator LT = al.listiterator(); While (lt.hasnext()) {system.out.println (lt.next()); } while (lt.hasprevious()) {system.out.println (lt.previous()); } // 4, judge system out. Println (al.contains (new student ("bird", 19)); //5, find system out. Println (al.indexof (new student ("Xiaohong", 13))); }

 

Source code analysis: default_ Capacity = 10 default capacity

Note: if no element is added to the set, the capacity is 0. After adding an element, the capacity is 10, which is 1.5 times of the original at each hole melting

Size number of actual elements

Add() add element

public boolean add(E e) {         ensureCapacityInternal(size + 1);  // Increments modCount!!         elementData[size++] = e;         return true;     }   private void ensureCapacityInternal(int minCapacity) {         ensureExplicitCapacity(calculateCapacity(elementData, 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);     }

LinkList

Consistent with ArrayList

Vector

Use the same method as ArrayList, but traverse differently, and have their own unique methods

//Traverse // use the enumerator enumeration elements = vector Elements(); While (elements.hasmoreelements()) {string o = (string) elements.nexterelement(); system.out.println (o); } // other methods // firstelement, lastelement, elementat (int index) are returned according to the subscript

 

generic paradigm

Java generics is a new feature introduced by JDK1.5. Its essence is parameterized types, which are passed as parameters

Common forms include generic classes, generic interfaces, and generic methods

Benefits: improve code reusability, prevent type conversion exceptions, and provide code security

Generic class

Public class mygeneric<t> {// use generic t //1 to create a variable public t t; //2 use generic t as the variable public void show (t t t) {// T T1 = new t(); the pump uses new because the type of t does not determine system.out.println (T); } // 3 the generic type is used as the return value of the method public t gett() {return T; }}

generic interface

Public interface myinterface<t> {string name = "Zhang San"; t serve (t t t); } // the interface implements public class myinterfaceimpl implements myinterface<string> {@override public string serve (string s) {system.out.println (s); return s; }} public class myinterfactimpl2<t> implements myinterface<t> {@override public t serve (t t) {system.out.println (T); return T; }

 

generic method

Public class mygenericmethod {// generic method public <t> void show (t t) {system.out.println (T); } public <t> t set (t t) {return T; }}

 

Generic Collections: parameterized, type safe collections enforce that type elements must be consistent. Features: it can be checked at compile time instead of throwing an exception at run time. Type conversion is not necessary during access. Different generics cannot be assigned to each other. There is no polymorphism

ArrayList<String> arrayList = new ArrayList<>();

Call the above generic classes, generic interfaces, and generic methods

//Create objects using generics. // Note: 1. Only reference objects can be used for generics. 2. Different generic objects cannot replicate with each other. // the generic object mygeneric mygeneric = new mygeneric(); Mygeneric T = "hello"; Mygeneric Show ("Hello everyone"); String string = mygeneric Gett(); Mygeneric mygeneric1 = new mygeneric<> (); Mygeneric1.t = 2000; Mygeneric1.show (30); Integer t = mygeneric1 Gett()// Generic interface //mygeneric mygeneric2 = mygeneric1; An error occurred, different generic object myinterfaceimpl impl = new myinterfaceimpl(); impl. Serve ("XXXXXXX"); Myinterfactimpl2 impl2 = new myinterfactimpl2<> (); Impl2.serve (200)// Generic method mygenericmethod mygenericmethod = new mygenericmethod()// All three methods can be used. What is given becomes what mygenericmethod Show ("China refueling"); Mygenericmethod Show (200); Mygenericmethod Show (3.14);}

 

Set

Hashset:Calculate the storage location of the element based on the hashcode. When the hash code of the stored element is the same, equals will be called for confirmation. If it is true, the latter will be rejected for storage.

TreeSet:Based on the arrangement order, the elements are not repeated. The sortedset interface is implemented to automatically sort the set elements. The type of the element object must implement the comparable interface to specify the sort order.

Map collection

image-20220313162101172

Features of map interface: 1 Used to store any key value pair

  1. Key: unordered, no subscript, no repetition (unique)

  2. Value: unordered, no subscript, repetition allowed

HashMap

apply

//Create object HashMap HashMap = new HashMap < > ()// Add the element student S1 = new student ("smoked Wukong", 100); Hashmap Put (S1, "Shanghai")// Delete element hashmap Remove (S1)// Traverse //1, enhance for key Set() for (student key: hashmap.keyset()) {system.out.println (key.tostring() + "= =" +hashmap.get (key));}// 2. Enhanced for entryset() for (map.entry entry: hashmap.entryset()) {system.out.println (entry.getkey() + "= =" +entry.getvalue());}// Judge system out. Println (hashmap.containskey (S1)); System. out. Println (hashmap.containsvalue ("Caoxian");

 

Source code analysis

(1) When HashMap is just created, the table is null. To save space, when the first original is added, the table capacity is adjusted to 16 (2) when the number of elements is greater than the threshold (16*0.75=12), the capacity will be expanded. After the expansion, the size will be 2 times that of the original. The purpose is to reduce the number of adjusted elements (3) JDK1.8 when the length of each chain is greater than 8 and the number of elements is greater than or equal to 64, it will be adjusted to a red black tree, Riddle solution to improve execution efficiency (4) JDK1.8 when the length of the linked list is less than 6, it will be adjusted to the linked list (5) before JDK1.8, the header is inserted in the linked list, and after JDK1.8, the tail is inserted

Note: the relationship between HashMap and HashSet is actually the same thing, both of which are hashmaps

//Hashmap Put (S1, "turret"); Do not add //hashmap Put (new student ("smoked Wukong", 100), "gun tower"); Add // if you don't want to add it, "de duplication". Rewrite hashcode() and equals() // delete for the same reason

 

TreeMap

Method: consistent with HashMap

Note: because the storage structure of the tree map is a red black tree, it is necessary to compare when adding elements

//Method 1: use comparator to customize comparison treemap treemap = new treemap < > (New comparator() {@override public int compare (student O1, student O2) {int N1 = o1.getstudo() - o2.getstudo(); int N2 = o1.getname(). CompareTo (o2.getname()); return N1 = = 0? N2: N1;}})// Method 2: inherit comparable in student class and override comparetopublic class student implements comparable{ 	 @ Override public int CompareTo (person o) {int N1 = this.name.compareto (o.getname()); int N2 = this.age-o.getage(); return n1==0? N2: N1;}

 

Collections tool class

method:

ArrayList list = new arraylist<> (); Collections. Sort (list); Int i = collections Binarysearch (list, 26)// If it cannot be found, a negative value collections Copy (DeST, list); Collections. Reverse (list); Collections. Shuffle (list); Integer[] arr = list ToArray (New integer[0]); List List2 = arrays Aslist (Name2);
  1. Sort sort

  2. Binarysearch binary search. If the returned subscript is found, the returned negative value is not found

  3. Copy (target, source) ensure that the target has self purchased capacity before replication

  4. Reversereverse

  5. Shuffle

  6. ToArray (New integer[0]) list to array

  7. Aslist (array name) array to set

 

Collection summary

Concept of set:Object containers, like arrays, define common methods for operating on multiple objects

List set:Orderly, subscript, and repeatable elements. (ArrayList [storage structure: array], LinkedList [storage structure: bidirectional linked list], vector [storage structure: array])

Set set:Unordered, no subscript, element cannot be repeated. (HashSet [storage structure: array + linked list + red black tree], TreeSet [storage structure: red black tree])

Map collection:A pair of data is stored in an unordered manner without subscript. The key cannot be repeated, and the value can be repeated (HashMap [storage structure: array + linked list + red black tree], hashtable [obsolete], treemap [storage structure: red black tree])

be careful: 1. Because the storage structure of TreeSet and treemap is a red black tree, it is necessary to compare the sizes before adding elements. Therefore, when adding objects of some classes, it is necessary to inherit the comparable interface, rewrite the CompareTo () method, or use the comparator method for customized comparison when creating objects

//Use the anonymous internal class of comparator to perform customized comparison TreeSet treeset1 = new treeset<> (New comparator() {@override public int compare (person O1, person O2) {int n1= o1.getage() - o2.getage(); int N2 = o1.getname(). CompareTo (o2.getname()); return n1===0? N1: N2;}});

 

  1. The relationship between HashMap and HashSet is actually the same thing, both of which are hashmaps. Similarly, treemap and TreeSet are the same thing, both of which are treemaps.

  2. Student S3 = new student ("brush monk", 249); Hashmap Put (S3, "Beijing")// Hashmap Put (S3, "turret"); Do not add //hashmap Put (new student ("brush monk", 249), "turret"); Add // if you don't want to add it, "de duplication". Override hashcode() and equals()

Collections:Collection tool class, which defines common collection methods other than storage.