Origin of collection
-
When a single data content needs to be recorded in a Java program, a variable is declared.
-
When you need to record multiple data contents of the same type in a Java program, declare a one-dimensional array.
-
When you need to record multiple data contents of different types in a Java program, create an object.
-
When you need to record multiple object data of the same type in a Java program, create an object array. You can also create a collection
-
When you need to record multiple object data of different types in a Java program, prepare a collection.
Frame structure of collection
-
The top-level framework in Java is the java.util.Collection collection and java.util.Map collection.
-
The basic unit of accessing elements in the Collection is a single element.
-
The basic unit of accessing elements in the Map set is a single pair of elements.
Generic mechanism
(1) Basic concepts
- Generally, different types of objects can be stored in the collection because all objects are placed as Object types. Therefore, when taking out elements from the collection, they are also Object types. In order to express the real data type of the element, forced type conversion is required, and forced type conversion may cause type conversion exceptions.
- In order to avoid the above errors, a generic mechanism is added from Java 5, that is, the method of < data type > is used on the right side of the collection name to specify the element types that can be stored in the collection. If other types of elements are put in, an error will be compiled.
- Generics are only valid at compile time and do not distinguish between types at run time.
(2) Underlying principle
-
The essence of generics is parameterized type, that is, let the data type be passed as a parameter, where e is equivalent to the formal parameter responsible for occupying bits. When using the set, the data type in < > is equivalent to the actual parameter, which is used to initialize the formal parameter E, so that all e in the set can be replaced by the actual parameter. Because the actual parameter can pass a wide variety of data types, Hence the name generic.
-
For example:
code | explain |
---|---|
![]() | Where i is called the formal parameter, which is responsible for the occupation, and E is called the formal parameter, which is responsible for the occupation |
![]() | Where E is called the formal parameter and is responsible for the occupation |
import java.util.LinkedList; import java.util.List; public class ListGenericTest { public static void main(String[] args) { // 1. Prepare a List collection that supports generic mechanism, and explicitly require the elements in the collection to be of String type List<String> lt1 = new LinkedList<String>(); // 2. Add elements to the collection and print lt1.add("one"); System.out.println("lt1 = " + lt1); // [one] //lt1.add(2); Error // 3. Get the elements in the collection and print them String s = lt1.get(0); System.out.println("The obtained elements are:" + s); // one System.out.println("----------------------------------------------------"); // 2. Prepare a List collection that supports Integer type List<Integer> lt2 = new LinkedList<Integer>(); lt2.add(1); lt2.add(2); //lt2.add("3"); Error System.out.println("lt2 = " + lt2); // [1, 2] Integer integer = lt2.get(0); System.out.println("The obtained elements are:" + integer); // 1 System.out.println("----------------------------------------------------"); // A new feature from Java 7: the diamond feature is the data type in the following < >, which can be omitted List<Double> lt3 = new LinkedList<>(); // Written examination site // Trying to assign the value of lt1 to lt3, that is, to overwrite the original value in lt3, the result is an error: different types are supported in the collection //lt3 = lt1; Error } }
lt1 = [one] The obtained elements are: one ---------------------------------------------------- lt2 = [1, 2] The obtained element is: 1 ----------------------------------------------------
(2) Custom generic interface
- The difference between generic interfaces and ordinary interfaces is that a type parameter list is added later. There can be multiple type parameters, such as < e, t,... >, etc.
(3) Custom generic class
- The difference between generic classes and ordinary classes is that a type parameter list is added after the class name. There can be multiple type parameters, such as < e, t,... >, etc.
- When instantiating a generic class, you should specify a specific data type and reference the data type instead of the basic data type.
- The parent class has generics, and the child class can choose to keep generics or specify generic types.
- The subclass must be a "rich second generation". In addition to specifying or retaining the generics of the parent class, the subclass can also add its own generics
/** * The user-defined generic class Person, where T is equivalent to the formal parameter, which is responsible for the occupation, and the specific value is determined by the actual parameter * @param <T> It can be regarded as a data type named T */ public class Person<T> { private String name; private int age; private T gender; public Person() { } public Person(String name, int age, T gender) { this.name = name; this.age = age; this.gender = gender; } 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; } // It is not a generic method. This method cannot be decorated with the static keyword, because the T in this method can only be typed explicitly when the new object is used public /*static*/ T getGender() { return gender; } public void setGender(T gender) { this.gender = gender; } // The user-defined method prints out all the elements in the array specified by the parameter public static <T1> void printArray(T1[] arr) { for (T1 tt: arr) { System.out.println("tt = " + tt); } } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + ", gender=" + gender + '}'; } }
public class PersonTest { public static void main(String[] args) { // 1. Declare that the reference of Person type points to the object of Person type Person p1 = new Person("zhangfei", 30, "male"); // 2. Characteristics of printing object System.out.println(p1); // zhangfei 30 male System.out.println("-----------------------------------"); // 3. Specify the data type while creating the object to initialize T Person<String> p2 = new Person<>(); p2.setGender("female"); System.out.println(p2); // Null 0 female System.out.println("-----------------------------------"); // 4. Use Boolean type as the type of gender Person<Boolean> p3 = new Person<>(); p3.setGender(true); System.out.println(p3); // null 0 true System.out.println("-----------------------------------"); // 5. Call generic methods for testing Integer[] arr = {11, 22, 33, 44, 55}; Person.printArray(arr); // 11 22 33 44 55 } }
Person{name='zhangfei', age=30, gender=male} ----------------------------------- Person{name='null', age=0, gender=female} ----------------------------------- Person{name='null', age=0, gender=true} ----------------------------------- tt = 11 tt = 22 tt = 33 tt = 44 tt = 55
//public class SubPerson extends Person {/ / generic types are not reserved and no type is specified. At this time, T in the Person class defaults to Object type //Public class subperson extensions Person < String > {/ / generic types are not reserved, but generic types are specified. At this time, T in the Person class is specified as String type //Public class subperson < T > extends person < T > {/ / the generic type of the parent class is reserved. You can specify the type of T when constructing the object public class SubPerson<T, T1> extends Person<T> { // Keep the generics of the parent class and add new generics to the child class }
public class SubPersonTest { public static void main(String[] args) { // 1. Declare that the reference of SubPerson type points to the object of SubPerson type and call the set method to test //Subperson < string > SP1 = new subperson(); error: generic type is not supported in subperson class SubPerson sp1 = new SubPerson(); sp1.setGender("female"); System.out.println("----------------------------------------"); //SubPerson<Boolean> sp2 = new SubPerson<>(); SubPerson<Boolean, String> sp2 = new SubPerson<>(); sp2.setGender(true); } }
(4) Custom generic method
-
Generic method is that when we input parameters, we input generic parameters instead of specific parameters. We need to instantiate the generic parameters when calling this generic method.
-
Format of generic method:
[access rights] < generic > return value type method name ([Generic identification parameter name]) {method body;}
-
When using generic parameters in static methods, we need to define static methods as generic methods
(5) The embodiment of generics in inheritance
- If B is A subclass or sub interface of A and G is A class or interface with generic declaration, G is not A subtype of G!
For example, String is a subclass of Object, but List is not a subclass of List.
(6) Use of wildcards
-
Sometimes we want the type passed in to be within a specified range, so we can use generic wildcards.
-
For example, the type passed in before is required to be of Integer type, but later the business needs the parent class of Integer, and the Number class can also be passed in.
-
There are three wildcard forms in generics:
<? > unrestricted wildcard: indicates that we can pass in any type of parameter.
<? Extensions E > indicates that the upper bound of the type is e, which can only be e or a subclass of E.
<? Super E > indicates that the lower bound of the type is e, which can only be e or the parent of E.
public class Animal { }
public class Dog extends Animal { }
import java.util.LinkedList; import java.util.List; public class GenericTest { public static void main(String[] args) { // 1. Declare two List type collections for testing List<Animal> lt1 = new LinkedList<>(); List<Dog> lt2 = new LinkedList<>(); // Trying to assign the value of lt2 to lt1, that is, conversion from list < dog > type to list < animal > type occurs //LT1 = LT2; error: there is no parent-child relationship between types System.out.println("---------------------------------------------"); // 2. Use wildcards as the public parent of generic types List<?> lt3 = new LinkedList<>(); lt3 = lt1; // Conversion from list < animal > type to list <? > type can occur lt3 = lt2; // Conversion from list < dog > type to list <? > type can occur // Add and get elements to the public parent class //lt3.add(new Animal()); Error: cannot store an object of type animal //lt3.add(new Dog()); Error: can't store dog type objects. Adding elements is not supported Object o = lt3.get(0); // ok, it supports the acquisition of elements, which are all treated as Object types System.out.println("---------------------------------------------"); // 3. Use restricted wildcards List<? extends Animal> lt4 = new LinkedList<>(); // Element addition is not supported //lt4.add(new Animal()); //lt4.add(new Dog()); //lt4.add(new Object()); // Get element Animal animal = lt4.get(0); System.out.println("---------------------------------------------"); List<? super Animal> lt5 = new LinkedList<>(); lt5.add(new Animal()); lt5.add(new Dog()); //lt5.add(new Object()); Error: exceeds the range of Animal type Object object = lt5.get(0); } }
The maximum value in the set is: 50 The minimum value in the set is: 10 lt1 = [45, 50, 20, 30, 10] After exchange: lt1 = [10, 50, 20, 30, 45] After sorting: lt1 = [10, 20, 30, 45, 50] After random replacement: lt1 = [30, 20, 45, 10, 50] lt1 The size of the is: 5 lt2 The size of the is: 10 lt2 = [30, 20, 45, 10, 50, null, null, null, null, null]
Two diagrams of the collection framework
Collection collection
(1) Basic concepts of Collection
- The java.util.Collection interface is the parent interface of the List interface, Queue interface and Set interface. Therefore, the methods defined in this interface can be used to operate not only the List Set, but also the Queue Set and Set set Set.
(2) Collection common methods
Method declaration | Function introduction |
---|---|
boolean add(E e); | Add objects to the collection |
boolean addAll(Collection<? extends E> c) | Used to add all elements in the set c specified by the parameter to the current set |
boolean contains(Object o); | Determines whether the specified object is included |
boolean containsAll(Collection<?> c) | Determines whether all objects specified by the parameter are included |
boolean retainAll(Collection<?> c) | Keep all objects that exist in the current collection and in the parameter collection |
boolean remove(Object o); | Delete object from collection |
boolean removeAll(Collection<?> c) | Deletes all objects specified by the parameter from the collection |
void clear(); | Empty collection |
int size(); | Returns the number of containing objects |
boolean isEmpty(); | Judge whether it is empty |
boolean equals(Object o) | Judge whether they are equal |
int hashCode() | Gets the hash code value of the current collection |
Object[] toArray() | Convert collection to array |
Iterator iterator() | Gets the iterator for the current collection |
(1) The underlying principle of the ArrayList class
import java.util.Objects; public class Person { private String name; private int age; public Person() { } public Person(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 boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Person person = (Person) o; return age == person.age && Objects.equals(name, person.name); } @Override public int hashCode() { return Objects.hash(name, age); } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; public class CollectionTest { public static void main(String[] args) { // 1. Prepare a Collection set for merge printing //Collection c1 = new Collection(); // Interfaces cannot be instantiated, that is, objects cannot be created // The reference of interface type points to the object implementing the class, forming polymorphism Collection c1 = new ArrayList(); // Automatically call the toString method and call the toString method in the ArrayList class. The default print format is: [element value 1, element value 2,...] System.out.println("The elements in the collection are:" + c1); // [nothing] System.out.println("--------------------------------------------------------"); // 2. Add a single element to the collection and print boolean b1 = c1.add(new String("one")); System.out.println("b1 = " + b1); // true System.out.println("The elements in the collection are:" + c1); // [one] b1 = c1.add(Integer.valueOf(2)); System.out.println("b1 = " + b1); // true System.out.println("The elements in the collection are:" + c1); // [one, 2] b1 = c1.add(new Person("zhangfei", 30)); System.out.println("b1 = " + b1); // true // When printing all elements in the collection, it is essentially printing each object in the collection, that is, making each object call the toString method of the corresponding class System.out.println("The elements in the collection are:" + c1); // [one, 2, Person{name='zhangfei', age=30}] System.out.println("--------------------------------------------------------"); // 3. Add multiple elements to the collection and print Collection c2 = new ArrayList(); c2.add("three"); // Constant pool c2.add(4); // Automatic packing mechanism System.out.println("c2 = " + c2); // [three, 4] // All elements in c2 are added to set c1, that is, the elements in set c2 are added to set c1 one by one b1 = c1.addAll(c2); // Indicates that the set c2 as a whole is added to the set c1 as an element //b1 = c1.add(c2); System.out.println("b1 = " + b1); // [one, 2, Person{name='zhangfei', age=30}, three, 4] [one, 2, Person{name='zhangfei', age=30}, [three, 4]] System.out.println("c1 = " + c1); System.out.println("--------------------------------------------------------"); // 4. Judge whether the set contains a single element specified by the parameter b1 = c1.contains(new String("one")); System.out.println("b1 = " + b1); // true b1 = c1.contains(new String("two")); System.out.println("b1 = " + b1); // false b1 = c1.contains(Integer.valueOf(2)); System.out.println("b1 = " + b1); // true b1 = c1.contains(Integer.valueOf(3)); System.out.println("b1 = " + b1); // false // The working principle of the contains method is: Objects.equals(o, e), where o represents the formal parameter of the contains method and e represents each element in the collection // That is, the working principle of contains is to compare the parameter object with the existing elements in the collection in turn, and call the equals method in Objects in the way of comparison // The working principle of equals is as follows: /* public static boolean equals(Object a, Object b) { Where a represents the Person object and b represents the existing object in the collection return (a == b) || (a != null && a.equals(b)); The first way to include an element is that the Person object has the same address as an existing object in the collection The second method is: if the Person object is not empty, the Person object calls the equals method to be equal to the existing elements in the collection } */ // When the equals method is not overridden in the Person class, the equals method inherited from the Object class is called to compare the addresses of the two objects, false // When the equals method is rewritten in the Person class, the rewritten version is called to compare the contents of the two objects b1 = c1.contains(new Person("zhangfei", 30)); System.out.println("b1 = " + b1); // true false System.out.println("--------------------------------------------------------"); // [one, 2, Person{name='zhangfei', age=30}, three, 4] System.out.println("c1 = " + c1); // 5. Judge whether the current set contains all elements of the set specified by the parameter Collection c3 = new ArrayList(); c3.add(4); System.out.println("c3 = " + c3); // [4] // It is determined whether the set c1 contains all the elements in the set c3 b1 = c1.containsAll(c3); System.out.println("b1 = " + b1); // true c3.add("five"); System.out.println("c3 = " + c3); // [4, five] // Judge whether the set c1 contains all the elements in the set c3. Only when all the elements in the set c3 appear in the set c1 will it return true, otherwise it will be false b1 = c1.containsAll(c3); System.out.println("b1 = " + b1); // false // Written examination site System.out.println("c2 = " + c2); // [three, 4] b1 = c1.containsAll(c2); System.out.println("b1 = " + b1); // true false // It is determined whether the set c1 has an element in the unit of the whole set c2 b1 = c1.contains(c2); System.out.println("b1 = " + b1); // false true System.out.println("--------------------------------------------------------"); // 6. Calculate the intersection of two sets and keep it in the current set System.out.println("c2 = " + c2); // [three, 4] System.out.println("c3 = " + c3); // [4, five] // That is to say, let the set intersect with itself, or let itself, that is, the elements in the current set have not changed b1 = c2.retainAll(c2); System.out.println("b1 = " + b1); // false indicates that the elements in the current collection have not changed System.out.println("c2 = " + c2); // [three, 4] // The intersection of sets c2 and c3 is calculated and retained in set c2 to replace the original values in set c2 b1 = c2.retainAll(c3); System.out.println("b1 = " + b1); // true the elements of the current collection have changed System.out.println("c2 = " + c2); // [4] System.out.println("c3 = " + c3); // [4, five] System.out.println("--------------------------------------------------------"); // 7. Delete a single element in the collection // [one, 2, Person{name='zhangfei', age=30}, three, 4] System.out.println("c1 = " + c1); // Deletes a single element specified by the parameter b1 = c1.remove(1); System.out.println("b1 = " + b1); // false // [one, 2, Person{name='zhangfei', age=30}, three, 4] System.out.println("c1 = " + c1); b1 = c1.remove("one"); System.out.println("b1 = " + b1); // true // [2, Person{name='zhangfei', age=30}, three, 4] System.out.println("c1 = " + c1); // How the remove method works: Objects.equals(o, e) b1 = c1.remove(new Person("zhangfei", 30)); System.out.println("b1 = " + b1); // true // [2, three, 4] System.out.println("c1 = " + c1); System.out.println("--------------------------------------------------------"); // 8. Delete all elements in the collection System.out.println("c3 = " + c3); // [4, five] // Deleting all elements in set c3 from set c1 is essentially deleting elements one by one. If there are elements, they will be deleted, otherwise they will not be deleted b1 = c1.removeAll(c3); System.out.println("b1 = " + b1); // true // [2, three] System.out.println("c1 = " + c1); System.out.println("c3 = " + c3); // [4, five] // Delete the whole object c3 from the written examination site b1 = c1.remove(c3); System.out.println("b1 = " + b1); // false System.out.println("c1 = " + c1); // [2, three] System.out.println("--------------------------------------------------------"); // 9. Test other methods in the collection. ctrl+n can directly search and open the source code of the class. Use ctrl+f12 to search the methods in the class System.out.println("The number of elements in the collection is:" + c1.size()); // 2 System.out.println(0 == c1.size() ? "The collection is empty": "The collection is not empty"); // No time System.out.println(c1.isEmpty()? "The collection is empty": "The collection is not empty"); // No time // Empty all elements in the collection c1.clear(); System.out.println("The number of elements in the collection is:" + c1.size()); // 0 System.out.println(0 == c1.size() ? "The collection is empty": "The collection is not empty"); // It's empty System.out.println(c1.isEmpty()? "The collection is empty": "The collection is not empty"); // It's empty // Prepare two sets and determine whether they are equal Collection c4 = new ArrayList(); c4.add(1); c4.add(2); System.out.println("c4 = " + c4); // [1, 2] Collection c5 = new ArrayList(); c5.add(1); c5.add(2); c5.add(3); System.out.println("c5 = " + c5); // [1, 2, 3] // Judge whether they are equal b1 = c4.equals(c5); System.out.println("b1 = " + b1); // true false System.out.println("--------------------------------------------------------"); // 10. To realize the conversion between collection and array types, it is generally considered that collection is a structure used to replace array // Realize the conversion from collection to array type Object[] objects = c5.toArray(); // Prints all elements in the array System.out.println("The elements in the array are:" + Arrays.toString(objects)); // [1, 2, 3] // Implement the conversion from array type to collection type Collection objects1 = Arrays.asList(objects); System.out.println("The elements in the collection are:" + objects1); // [1, 2, 3] } }
The elements in the collection are:[] -------------------------------------------------------- b1 = true The elements in the collection are:[one] b1 = true The elements in the collection are:[one, 2] b1 = true The elements in the collection are:[one, 2, Person{name='zhangfei', age=30}] -------------------------------------------------------- c2 = [three, 4] b1 = true c1 = [one, 2, Person{name='zhangfei', age=30}, three, 4] -------------------------------------------------------- b1 = true b1 = false b1 = true b1 = false b1 = true -------------------------------------------------------- c1 = [one, 2, Person{name='zhangfei', age=30}, three, 4] c3 = [4] b1 = true c3 = [4, five] b1 = false c2 = [three, 4] b1 = true b1 = false -------------------------------------------------------- c2 = [three, 4] c3 = [4, five] b1 = false c2 = [three, 4] b1 = true c2 = [4] c3 = [4, five] -------------------------------------------------------- c1 = [one, 2, Person{name='zhangfei', age=30}, three, 4] b1 = false c1 = [one, 2, Person{name='zhangfei', age=30}, three, 4] b1 = true c1 = [2, Person{name='zhangfei', age=30}, three, 4] b1 = true c1 = [2, three, 4] -------------------------------------------------------- c3 = [4, five] b1 = true c1 = [2, three] c3 = [4, five] b1 = false c1 = [2, three] -------------------------------------------------------- The number of elements in the collection is: 2 The collection is not empty The collection is not empty The number of elements in the collection is: 0 The collection is empty The collection is empty c4 = [1, 2] c5 = [1, 2, 3] b1 = false -------------------------------------------------------- The elements in the array are:[1, 2, 3] The elements in the collection are:[1, 2, 3]
Iterator interface
(1) Basic concepts
- The java.util.Iterator interface is mainly used to describe the iterator object, which can traverse all elements in the Collection.
- The java.util.Collection interface inherits the Iterator interface, so all implementation classes that implement the Collection interface can use the Iterator object.
(2) Common methods
Method declaration | Function introduction |
---|---|
boolean hasNext() | Determine whether there are elements in the collection that can be iterated / accessed |
E next() | Used to take out one element and point to the next |
void remove() | Used to delete the last element accessed |
Case title
- How to use iterators to achieve the printing effect of toString method?
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class CollectionPrintTest { public static void main(String[] args) { // 1. Prepare a Collection and print after putting elements in it Collection c1 = new ArrayList(); c1.add("one"); c1.add(2); c1.add(new Person("zhangfei", 30)); // Traversal method 1: automatically call the toString method as a whole of String type System.out.println("c1 = " + c1); // [one, 2, Person{name='zhangfei', age=30}] System.out.println("------------------------------------------------"); // 2. Traversal mode 2: it is more flexible to use iterators to traverse all elements in the collection // 2.1 get iterator objects in the current collection Iterator iterator1 = c1.iterator(); /* // 2.2 Determine whether any elements can be accessed System.out.println(iterator1.hasNext()); // true // 2.3 Take out one element and point to the next System.out.println("The obtained elements are: "+ iterator1.next()); // one System.out.println(iterator1.hasNext()); // true System.out.println("The obtained element is: "+ iterator1. Next())// two System.out.println(iterator1.hasNext()); // true System.out.println("The obtained elements are: "+ iterator1.next()); // Person{name='zhangfei', age=30} System.out.println(iterator1.hasNext()); // false System.out.println("The obtained element is: "+ iterator1.next())// Compile ok and run NoSuchElementException. There is no such element exception */ while (iterator1.hasNext()) { System.out.println("The obtained elements are:" + iterator1.next()); } System.out.println("------------------------------------------------"); // Since the last loop has brought the iterator to the end, you need to reset the iterator iterator1 = c1.iterator(); // 3. Use iterator to simulate the printing effect of toString method StringBuilder sb1 = new StringBuilder(); sb1.append("["); while (iterator1.hasNext()) { Object obj = iterator1.next(); // When the obtained element is the last element, the spliced element is bracketed if (!iterator1.hasNext()) { sb1.append(obj).append("]"); } else { // Otherwise, concatenate elements with commas and spaces sb1.append(obj).append(",").append(" "); } } // [one, 2, Person{name='zhangfei', age=30}] System.out.println("c1 = " + sb1); System.out.println("------------------------------------------------"); // 4. Continuously get the element in the set and judge. When the element value is "one", delete the element iterator1 = c1.iterator(); while (iterator1.hasNext()) { Object obj = iterator1.next(); if("one".equals(obj)) { iterator1.remove(); //There is no problem deleting elements using the remove method of the iterator //c1.remove(obj); // Use the remove method of the collection to compile ok, and a concurrent modificationexception occurs when running } } System.out.println("The elements in the collection after deletion are:" + c1); // [2, Person{name='zhangfei', age=30}] } }
c1 = [one, 2, Person{name='zhangfei', age=30}] ------------------------------------------------ The obtained elements are: one The obtained element is: 2 The obtained elements are: Person{name='zhangfei', age=30} ------------------------------------------------ c1 = [one, 2, Person{name='zhangfei', age=30}] ------------------------------------------------ The elements in the collection after deletion are:[2, Person{name='zhangfei', age=30}]
for each loop
(1) Basic concepts
- Java 5 introduced an enhanced for loop statement, which can apply the traversal of arrays and collections. It is a "simplified version" of classical iteration.
(2) Syntax format
For (element type variable name: array / collection name){
Circulatory body;
}
(3) Execution process
- Continuously take an element from the array / collection, assign it to the variable name, and execute the loop body until all the elements are taken.
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; public class CollectionPrintTest { public static void main(String[] args) { // 1. Prepare a Collection and print after putting elements in it Collection c1 = new ArrayList(); c1.add("one"); c1.add(2); c1.add(new Person("zhangfei", 30)); // 5. Use the for each structure to traverse the elements in the set and array. The code is simple and the method is flexible // From the debugging source code, we can see that this method is indeed a simplified version of the iterator for (Object obj : c1) { System.out.println("The extracted elements are:" + obj); } int[] arr = new int[] {11, 22, 33, 44, 55}; for (int i : arr) { System.out.println("i = " + i); i = 66; // Modifying the value of the local variable i does not modify the value of the elements in the array } System.out.println("The elements in the array are:" + Arrays.toString(arr)); } }
The extracted elements are: one The extracted elements are: 2 The extracted elements are: Person{name='zhangfei', age=30} i = 11 i = 22 i = 33 i = 44 i = 55 The elements in the array are:[11, 22, 33, 44, 55]
List collection
(1) Basic concepts
-
The java.util.List Collection is a subset of the Collection collection. Duplicate elements are allowed in the Collection and are placed in order.
The main implementation classes of this collection include ArrayList class, LinkedList class, Stack class and Vector class.
-
The bottom layer of ArrayList class uses dynamic array for data management, supports subscript access, and it is inconvenient to add or delete elements.
-
The bottom layer of the LinkedList class uses a two-way linked list for data management, which is inconvenient to access and convenient to add and delete elements.
-
It can be considered that the methods of ArrayList and LinkedList are exactly the same in logic, but there are some differences in performance. ArrayList is more suitable for random access and LinkedList is more suitable for insertion and deletion. This difference can be ignored when the performance requirements are not particularly harsh.
-
The bottom layer of Stack class uses dynamic array for data management. This class is mainly used to describe a data structure with last in first out characteristics, which is called Stack (last in first out LIFO).
-
The bottom layer of Vector class uses dynamic array for data management. Compared with ArrayList class, this class belongs to thread safe class with low efficiency, which is basically not used in future development
(2) Common methods
Method declaration | Function introduction |
---|---|
void add(int index, E element) | Adds an element to the specified location in the collection |
boolean addAll(int index, Collection<? extends E> c) | Add all elements to the collection |
E get(int index) | Gets the specified location element from the collection |
int indexOf(Object o) | Finds the object specified by the parameter |
int lastIndexOf(Object o) | Reversely finds the object specified by the parameter |
E set(int index, E element) | Modify the element at the specified location |
E remove(int index) | Deletes the element at the specified location |
List subList(int fromIndex, int toIndex) | Used to get the child List |
import java.util.ArrayList; import java.util.LinkedList; import java.util.List; public class ListTest { public static void main(String[] args) { // 1. Declare that a reference of List interface type points to an object of ArrayList type, forming polymorphism // It can be seen from the source code that the memory space of the array is not applied for when the new object List lt1 = new ArrayList(); // 2. Add elements to the collection and print // It can be seen from the source code that when calling the add method to add elements, a one-dimensional array with a length of 10 will be applied for the array. The expansion principle is: 1.5 times the original length lt1.add("one"); System.out.println("lt1 = " + lt1); // [one] System.out.println("----------------------------------------------------"); // 2. Declare that a reference of List interface type points to an object of LinkedList type, forming polymorphism List lt2 = new LinkedList(); lt2.add("one"); System.out.println("lt2 = " + lt2); // [one] } }
lt1 = [one] ---------------------------------------------------- lt2 = [one]
import java.util.LinkedList; import java.util.List; public class ListMethodTest { public static void main(String[] args) { // 1. Prepare a List set for merge printing List lt1 = new LinkedList(); System.out.println("lt1 = " + lt1); // [nothing] System.out.println("------------------------------------------"); // 2. Add elements to the collection and print // Adds an element to the beginning of the collection lt1.add(0, "one"); System.out.println("lt1 = " + lt1); // [one] // Adds an element to the end of the collection lt1.add(1, 3); System.out.println("lt1 = " + lt1); // [one, 3] // Adds an element to the middle of the collection lt1.add(1, "two"); System.out.println("lt1 = " + lt1); // [one, two, 3] System.out.println("------------------------------------------"); // 3. Get the element according to the subscript specified by the parameter String str1 = (String) lt1.get(0); System.out.println("The obtained elements are:" + str1); // one // Note: be careful when getting elements and casting them, because type conversion exceptions are easy to occur //String str2 = (String)lt1.get(2); / / compile ok and run ClassCastException type conversion exception //System.out.println("the obtained element is:" + str2); // 3 System.out.println("------------------------------------------"); // 4. Use the get method to get all the elements in the collection and print them StringBuilder sb1 = new StringBuilder(); sb1.append("["); for (int i = 0; i < lt1.size(); i++) { //Object obj = lt1.get(i); //System.out.println("the obtained element is:" + obj "); Object obj = lt1.get(i); // If the extracted element is the last element, splice the element value and] if (lt1.size()-1 == i) { sb1.append(obj).append("]"); } // Otherwise, splice elements with commas and spaces else { sb1.append(obj).append(",").append(" "); } } System.out.println("lt1 = " + sb1); // [one, two, 3] System.out.println("------------------------------------------"); // 5. Find the index position where the specified element appears System.out.println("one The index position of the first occurrence is:" + lt1.indexOf("one")); // 0 lt1.add("one"); System.out.println("lt1 = " + lt1); // [one, two, 3, one] System.out.println("one The index position where the reverse lookup first occurs is:" + lt1.lastIndexOf("one")); // 3 System.out.println("------------------------------------------"); System.out.println("lt1 = " + lt1); // [one, two, 3, one] // 6. Implement the modification of elements in the collection Integer it1 = (Integer) lt1.set(2, "three"); System.out.println("The modified elements are:" + it1); // 3 System.out.println("The elements in the modified set are:" + lt1); // [one, two, three, one] String str2 = (String) lt1.set(3, "four"); System.out.println("The modified elements are:" + str2); // one System.out.println("The elements in the modified set are:" + lt1); // [one, two, three, four] System.out.println("------------------------------------------"); // 7. Use the remove method to delete all elements in the collection //for (int i = 0; i < lt1.size(); /*i++*/) { /* for (int i = lt1.size()-1; i >= 0; i--) { //System.out.println("The deleted element is: "+ LT1. Remove (I)); / / one two three four after deleting the element, the following element will be filled //System.out.println("The deleted element is: "+ lt1.remove(0)); System.out.println("The deleted element is: "+ lt1.remove(i)); } System.out.println("The elements in the final set are: "+ lt1); / / [nothing]*/ System.out.println("------------------------------------------"); // 8. Get the subset in the current set, that is, get part of the content in the set. The subset and the current set share the same memory space // Means to get the elements in the current collection lt1 with subscripts from 1 to 3, including 1 but not 3 List lt2 = lt1.subList(1, 3); System.out.println("lt2 = " + lt2); // [two, three] // Delete the value of the element in lt2 str2 = (String) lt2.remove(0); System.out.println("The deleted elements are:" + str2); // two System.out.println("After deletion lt2 = " + lt2); // [three] System.out.println("After deletion lt1 = " + lt1); // [one, three, four] }
lt1 = [] ------------------------------------------ lt1 = [one] lt1 = [one, 3] lt1 = [one, two, 3] ------------------------------------------ The obtained elements are: one ------------------------------------------ lt1 = [one, two, 3] ------------------------------------------ one The index position of the first occurrence is: 0 lt1 = [one, two, 3, one] one The index position of the first occurrence of reverse lookup is: 3 ------------------------------------------ lt1 = [one, two, 3, one] The modified elements are: 3 The elements in the modified set are:[one, two, three, one] The modified elements are: one The elements in the modified set are:[one, two, three, four] ------------------------------------------ ------------------------------------------ lt2 = [two, three] The deleted elements are: two After deletion lt2 = [three] After deletion lt1 = [one, three, four]
(1) The underlying principle of the LinkedList class
(3) Case title
-
Prepare a Stack set, put the data 11, 22, 33, 44 and 55 on the Stack and print them in turn, then view the top elements of the Stack and print them, and then put all the data in the Stack out of the Stack and print them in turn.
-
Then prepare a Stack object, take the data out of the first Stack and put it into the second Stack, and then take it out of the second Stack and print it
Stack and queue characteristics
import java.util.Stack; public class StackTest { public static void main(String[] args) { // 1. Prepare an object of Stack type and print it Stack s1 = new Stack(); Stack s2 = new Stack(); System.out.println("s1 = " + s1); // [nothing] System.out.println("s2 = " + s2); // [nothing] System.out.println("-----------------------------------------------"); // 2. Stack and print data 11, 22, 33, 44 and 55 in turn for (int i = 1; i <= 5; i++) { Object obj = s1.push(i * 11); System.out.println("The stacked elements are:" + obj); //System.out.println("the elements in the stack are:" + S1)// 11 22 33 44 55 } System.out.println("-----------------------------------------------"); // 3. View the element value at the top of the stack and print it //Object obj2 = s1.peek(); //System.out.println("the obtained stack top element is:" + obj2 ")// fifty-five System.out.println("-----------------------------------------------"); // 4. Print all elements in the stack in turn int len = s1.size(); for (int i = 1; i <= len; i++) { Object to = s1.pop(); //System.out.println("the element out of the stack is:" + to ")// 55 44 33 22 11 s2.push(to); } System.out.println("-----------------------------------------------"); // 5. Finally print all elements in the stack //System.out.println("s1 = " + s1); // [nothing] System.out.println("-----------------------------------------------"); len = s2.size(); for (int i = 1; i <= len; i++) { Object to = s2.pop(); System.out.println("The elements out of the stack are:" + to); // 11 22 33 44 55 } } }
s1 = [] s2 = [] ----------------------------------------------- The elements on the stack are: 11 The stack elements are: 22 The stack elements are: 33 The elements on the stack are: 44 The stack element is: 55 ----------------------------------------------- ----------------------------------------------- ----------------------------------------------- ----------------------------------------------- The elements out of the stack are: 11 The elements out of the stack are: 22 The elements out of the stack are: 33 The elements out of the stack are: 44 The elements out of the stack are: 55
Queue collection
(1) Basic concepts
-
The Java.util.Queue Collection is a subset of the Collection collection Collection, which is in a horizontal relationship with the List Collection.
-
The of this set is mainly used to describe the data structure with first in first out characteristics, which is called the queue (FIFO).
-
The main implementation class of this collection is the LinkedList class, which has advantages in addition and deletion.
(2) Common methods
Method declaration | Function introduction |
---|---|
boolean offffer(E e) | Add an object to the end of the queue, and return true if the addition is successful |
E poll() | Deletes and returns an element from the head of the queue |
E peek() | Returns the element at the head of the queue (but does not delete it) |
(3) Case title
- Prepare a Queue set, Queue and print the data 11, 22, 33, 44 and 55 in turn, then view the first element of the Queue and print, and then Queue and print all the data in the Queue in turn.
import java.util.LinkedList; import java.util.Queue; public class QueueTest { public static void main(String[] args) { // 1. Prepare a Queue set for merge printing Queue queue = new LinkedList(); System.out.println("The elements in the queue are:" + queue); // [nothing] System.out.println("----------------------------------------------------------"); // 2. Queue and print data 11, 22, 33, 44 and 55 in turn for (int i = 1; i <= 5; i++) { boolean b1 = queue.offer(i * 11); //System.out.println("b1 = " + b1); System.out.println("The elements in the queue are:" + queue); // 11 22 33 44 55 } System.out.println("----------------------------------------------------------"); // 3. Then view the team head element and print it System.out.println("The first element is:" + queue.peek()); // 11 System.out.println("----------------------------------------------------------"); // 4. Then all data in the queue are queued and printed in turn int len = queue.size(); for (int i = 1; i <= len; i++) { System.out.println("The out of team elements are:" + queue.poll()); // 11 22 33 44 55 } System.out.println("----------------------------------------------------------"); // 5. View the final element in the queue System.out.println("The elements in the queue are:" + queue); // [nothing] } }
The elements in the queue are:[] ---------------------------------------------------------- The elements in the queue are:[11] The elements in the queue are:[11, 22] The elements in the queue are:[11, 22, 33] The elements in the queue are:[11, 22, 33, 44] The elements in the queue are:[11, 22, 33, 44, 55] ---------------------------------------------------------- The first element is: 11 ---------------------------------------------------------- The elements of leaving the team are: 11 The element of leaving the team is: 22 The element of leaving the team is: 33 The element of leaving the team is: 44 The element of leaving the team is: 55 ---------------------------------------------------------- The elements in the queue are:[]
Set set
(1) Basic concepts
(2) Common methods
Just refer to the methods in the Collection!
(3) Case title
Prepare a Set set to point to the HashSet object, add the element "two" to the Set and print, then add the element "one" to the Set and print, then add the element "three" to the Set and print, and then add "one" to the Set and print.
import java.util.HashSet; import java.util.Set; public class HashSetTest { public static void main(String[] args) { // 1. Declare a Set type reference to an object of HashSet type Set<String> s1 = new HashSet<>(); //Set<String> s1 = new LinkedHashSet<>(); // Use a double linked list to connect the put elements System.out.println("s1 = " + s1); // [nothing] System.out.println("----------------------------------------------------"); // 2. Add elements to the collection and print boolean b1 = s1.add("two"); System.out.println("b1 = " + b1); // true System.out.println("s1 = " + s1); // [two] // It can be seen from the print result that the elements are not placed in order (surface) b1 = s1.add("one"); System.out.println("b1 = " + b1); // true System.out.println("s1 = " + s1); // [one, two] [two, one] b1 = s1.add("three"); System.out.println("b1 = " + b1); // true System.out.println("s1 = " + s1); // [one, two, three] [two, one, three] // Validation elements cannot be repeated b1 = s1.add("one"); System.out.println("b1 = " + b1); // false System.out.println("s1 = " + s1); // [one, two, three] [two, one, three] } }
s1 = [] ---------------------------------------------------- b1 = true s1 = [two] b1 = true s1 = [one, two] b1 = true s1 = [one, two, three] b1 = false s1 = [one, two, three]
(4) How elements are put into the HashSet set set
-
Structure of hash table
-
Use the element to call the hashCode method to obtain the corresponding hash code value, and then calculate the index position of the element in the array by a hash algorithm
-
If there is no element in this position, you can put the element directly.
-
If there is an element in this position, the new element is used to compare the hash value with the existing element in turn. If the hash value is different, the element is directly put into the hash value.
-
If the hash value of the new element is the same as that of the existing element, the new element is used to call the equals method to compare with the existing element in turn. If they are equal, the addition of elements fails. Otherwise, the elements can be put directly into
-
Think: why do you need to override the hashCode method after overriding the equals method?
-
Parsing: when two elements call the equals method equally, it is proved that the two elements are the same. After rewriting the hashCode method, ensure that the hash code values obtained by the two elements are the same, and the index position generated by the same hash algorithm is the same. At this time, it is only necessary to compare with the existing elements in the index position, so as to improve efficiency and avoid the occurrence of duplicate elements.
-
The process of putting elements into a hash table
(5) Concept of TreeSet set
- Basic concepts of binary tree
- Basic concepts of ordered binary tree
- Red black tree
public class Student implements Comparable<Student> { private String name; private 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 + '}'; } @Override public int compareTo(Student o) { //return 0; // The calling object is equal to the parameter object, and the calling object is the newly added object //return -1; // The call object is smaller than the parameter object //return 1; // The call object is larger than the parameter object //return this.getName().compareTo(o.getName()); // Compare names //return this.getAge() - o.getAge(); // Comparative age /* int ia = this.getName().compareTo(o.getName()); if (0 == ia) { return this.getAge() - o.getAge(); } return ia; */ int ia = this.getName().compareTo(o.getName()); return 0 != ia? ia : this.getAge() - o.getAge(); } }
import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class TreeSetTest { public static void main(String[] args) { // 1. Prepare a TreeSet set for merge printing Set<String> s1 = new TreeSet<>(); System.out.println("s1 = " + s1); // [nothing] // 2. Add an object of type String to the collection and print it boolean b1 = s1.add("aa"); System.out.println("b1 = " + b1); // true System.out.println("s1 = " + s1); // [aa] b1 = s1.add("cc"); System.out.println("b1 = " + b1); // true System.out.println("s1 = " + s1); // [aa, cc] b1 = s1.add("bb"); System.out.println("b1 = " + b1); // true // Because the bottom layer of TreeSet set is implemented by red black tree, the elements have size order and are printed from small to large by default System.out.println("s1 = " + s1); // [aa, bb, cc] System.out.println("----------------------------------------------------------"); // 4. Prepare a comparator object and pass it to the constructor as a parameter // Anonymous inner class: Interface / parent type reference variable name = new interface / parent type () {override of method}; /* Comparator<Student> comparator = new Comparator<Student>() { @Override public int compare(Student o1, Student o2) { // o1 Represents a newly added object, o2 represents an existing object in the collection return o1.getAge() - o2.getAge(); // Indicates comparison by age } }; */ // Lambda expressions are supported from Java 8: (parameter list) - > {method body} Comparator<Student> comparator = (Student o1, Student o2) -> { return o1.getAge() - o2.getAge(); }; // 3. Prepare a TreeSet set and put it into the object of Student type and print it //Set<Student> s2 = new TreeSet<>(); Set<Student> s2 = new TreeSet<>(comparator); s2.add(new Student("zhangfei", 35)); s2.add(new Student("zhangfei", 30)); s2.add(new Student("guanyu", 35)); s2.add(new Student("liubei", 40)); System.out.println("s2 = " + s2); } }
s1 = [] b1 = true s1 = [aa] b1 = true s1 = [aa, cc] b1 = true s1 = [aa, bb, cc] ---------------------------------------------------------- s2 = [Student{name='zhangfei', age=30}, Student{name='zhangfei', age=35}, Student{name='liubei', age=40}]
Map collection
(1) Basic concepts of Map
(2) Common methods of Map
Method declaration | Function introduction |
---|---|
V put(K key, V value) | Store the Key Value pair into the Map. If the set already contains the Key, replace the Value corresponding to the Key. The return Value is the original Value corresponding to the Key. If there is no Key, return null |
V get(Object key) | Returns the Value object corresponding to the parameter Key. If it does not exist, it returns null |
boolean containsKey(Object key); | Judge whether the set contains the specified Key |
boolean containsValue (Object value); | Determines whether the collection contains the specified Value |
V remove(Object key) | Delete according to the key specified in the parameter |
Set keySet() | Returns the Set view of the keys contained in this map |
Collection values() | Returns the Set view of the values contained in this map |
Set<Map.Entry<K,V>> entrySet() | Returns the Set view of the mappings contained in this mapping |
import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; public class MapTest { public static void main(String[] args) { // 1. Prepare a Map set for merge printing Map<String, String> m1 = new HashMap<>(); // Automatically call the toString method. The default print format is: {key1=value1, key2=value2,...} System.out.println("m1 = " + m1); // {nothing} // 2. Add elements to the collection and print String str1 = m1.put("1", "one"); System.out.println("customary value The value is:" + str1); // null System.out.println("m1 = " + m1); // {1=one} str1 = m1.put("2", "two"); System.out.println("customary value The value is:" + str1); // null System.out.println("m1 = " + m1); // {1=one, 2=two} str1 = m1.put("3", "three"); System.out.println("customary value The value is:" + str1); // null System.out.println("m1 = " + m1); // {1=one, 2=two, 3=three} // The function of modification is realized str1 = m1.put("1", "eleven"); System.out.println("customary value The value is:" + str1); // one System.out.println("m1 = " + m1); // {1=eleven, 2=two, 3=three} System.out.println("-------------------------------------------------------------"); // 3. Implement the search operation of elements in the collection boolean b1 = m1.containsKey("11"); System.out.println("b1 = " + b1); // false b1 = m1.containsKey("1"); System.out.println("b1 = " + b1); // true b1 = m1.containsValue("one"); System.out.println("b1 = " + b1); // false b1 = m1.containsValue("eleven"); System.out.println("b1 = " + b1); // true String str2 = m1.get("5"); System.out.println("str2 = " + str2); // null str2 = m1.get("3"); System.out.println("str2 = " + str2); // three System.out.println("-------------------------------------------------------------"); // 4. Delete the elements in the collection str2 = m1.remove("1"); System.out.println("Deleted value Yes:" + str2); // eleven System.out.println("m1 = " + m1); // {2=two, 3=three} System.out.println("-------------------------------------------------------------"); // 5. Get all the key s in the Map Set and form the Set view Set<String> s1 = m1.keySet(); // Traverse all key s for (String ts : s1) { System.out.println(ts + "=" + m1.get(ts)); } System.out.println("-------------------------------------------------------------"); // 6. Get all the values in the Map Collection and form the Collection view Collection<String> co = m1.values(); for (String ts : co) { System.out.println("ts = " + ts); } System.out.println("-------------------------------------------------------------"); // 7. Obtain all key value pairs in the Map Set and form a Set view Set<Map.Entry<String, String>> entries = m1.entrySet(); for (Map.Entry<String, String> me : entries) { System.out.println(me); } } }
m1 = {} customary value The value is: null m1 = {1=one} customary value The value is: null m1 = {1=one, 2=two} customary value The value is: null m1 = {1=one, 2=two, 3=three} customary value The value is: one m1 = {1=eleven, 2=two, 3=three} ------------------------------------------------------------- b1 = false b1 = true b1 = false b1 = true str2 = null str2 = three ------------------------------------------------------------- Deleted value Yes: eleven m1 = {2=two, 3=three} ------------------------------------------------------------- 2=two 3=three ------------------------------------------------------------- ts = two ts = three ------------------------------------------------------------- 2=two 3=three
(3) How elements are put into the HashMap collection
(4) Related constants
(5) Principle of converting set set into Map set
Collections class
(1) Basic concepts of Collections
- The java.util.Collections class mainly provides static methods to operate on or return collections.
(2) Collections common methods
import java.util.*; public class CollectionsTest { public static void main(String[] args) { // 1. Prepare a merge initialization List<Integer> lt1 = Arrays.asList(10, 30, 20, 50, 45); // 2. Implement various operations of elements in the collection System.out.println("The maximum values in the collection are:" + Collections.max(lt1)); // 50 System.out.println("The minimum values in the set are:" + Collections.min(lt1)); // 10 // Implements the inversion of elements in a collection Collections.reverse(lt1); System.out.println("lt1 = " + lt1); // [45, 50, 20, 30, 10] // Realize the exchange of two elements Collections.swap(lt1, 0, 4); System.out.println("After exchange: lt1 = " + lt1); // [10, 50, 20, 30, 45] // Implement sorting of elements Collections.sort(lt1); System.out.println("After sorting: lt1 = " + lt1); // [10, 20, 30, 45, 50] // Random permutation Collections.shuffle(lt1); System.out.println("After random replacement: lt1 = " + lt1); // [30, 10, 45, 20, 50] random // Copy elements between collections //List<Integer> lt2 = new ArrayList<>(20); List<Integer> lt2 = Arrays.asList(new Integer[10]); System.out.println("lt1 The size of the is:" + lt1.size()); System.out.println("lt2 The size of the is:" + lt2.size()); // Means to copy the elements in lt1 to lt2 Collections.copy(lt2, lt1); System.out.println("lt2 = " + lt2); } }
The maximum value in the set is: 50 The minimum value in the set is: 10 lt1 = [45, 50, 20, 30, 10] After exchange: lt1 = [10, 50, 20, 30, 45] After sorting: lt1 = [10, 20, 30, 45, 50] After random replacement: lt1 = [45, 10, 20, 30, 50] lt1 The size of the is: 5 lt2 The size of the is: 10 lt2 = [45, 10, 20, 30, 50, null, null, null, null, null]