1. Collection overview
1.1 what is a collection? What's the usage?
An array is actually a collection. A collection is actually a container. Can be used to accommodate other types of data.
Why are collections used more in development?
A collection is a container and a carrier that can hold multiple objects at a time.
In the actual development, it is assumed that the database is connected, and there are 10 records in the database,
Then suppose you query these 10 records, and 10 records will be found in the java program
The data is encapsulated into 10 java objects, and then 10 java objects are placed in one
In the collection, the collection is transferred to the front end, and then the collection is traversed to transfer one data to another
The data show.
1.2. A collection cannot directly store basic data types. In addition, a collection cannot directly store java objects,
All stored in the collection are the memory addresses of java objects. (or the collection stores references.)
list.add(100); // Autoboxing Integer
be careful:
In java, a collection is a container and an object.
References are stored at any time in the collection.
1.3. For each different set in java, the underlying layer will correspond to different data structures. To different sets
Storing elements means putting data into different data structures. What is a data structure? Data storage
A structure is a data structure. Different data structures have different data storage methods. For example:
Array, binary tree, linked list, hash table
These are common data structures.
You put data into the set c1, maybe on the array.
If you put data into the set c2, it may be on the binary tree.
...
Using different sets is equivalent to using different data structures.
In the chapter of java collections, you don't need to be proficient in data structures. The data structure has been in java
Implemented. These common collection classes have been written. You just need to master how to use them? Under what circumstances
Which appropriate collection can be used.
new ArrayList(); Create a collection with an array at the bottom.
new LinkedList(); Create a collection object, and the underlying is a linked list.
new TreeSet(); Create a collection object with a binary tree at the bottom.
...
1.4. Under which package is the collection in the java JDK?
java.util.*;
All collection classes and collection interfaces are under the java.util package.
1.5. In order to let everyone master the content of the collection, it is best to recite the inheritance structure diagram of the collection!!!
You need to have an impression of what kind of structure the whole system is.
1.6 in java, collections are divided into two categories:
One is to store elements in a single way:
Store elements in a single way. The super parent interface in this kind of collection: java.util.Collection;
One is to store elements in key value pairs
Elements are stored in the form of key value pairs. The super parent interface in this kind of collection: java.util.Map;
2. Summary key points:
The first key point: recite the set inheritance structure diagram.
The second key point: test the common methods in the Collection interface several times.
Polymorphic traversal Collection
import java.util.ArrayList; import java.util.Collection; /* About the methods commonly used in the java.util.Collection interface. 1,Collection What elements can be stored in? Before using "generic", all subtypes of Object can be stored in the Collection. After using "generic", only a specific type can be stored in the Collection. Later in the Collection, we will learn the "generic" syntax. Don't worry about it for now. Everything can be stored in the Collection, As long as it is a subtype of Object. (basic data types cannot be directly stored in the collection, nor can they be stored in the collection.) java Object, just the memory address of the java object.) 2,Collection Common methods in boolean add(Object e) Add elements to the collection int size() Gets the number of elements in the collection void clear() Empty collection boolean contains(Object o) Judge whether the current collection contains elements o, return true if it contains elements, and return false if it does not boolean remove(Object o) Delete an element in the collection. boolean isEmpty() Judge whether the number of elements in the collection is 0 Object[] toArray() Call this method to convert a collection into an array. [as an understanding, not much is used.] */ public class CollectionTest01 { public static void main(String[] args) { // Create a collection object //Collection c = new Collection(); // The interface is abstract and cannot be instantiated. // polymorphic Collection c = new ArrayList(); // Test common methods in the Collection interface c.add(1200); // Auto Boxing (a new feature of Java 5) actually puts in the memory address of an object. Integer x = new Integer(1200); c.add(3.14); // Automatic packing c.add(new Object()); c.add(new Student()); c.add(true); // Automatic packing // Gets the number of elements in the collection System.out.println("The number of elements in the collection is:" + c.size()); // 5 // Empty collection c.clear(); System.out.println("The number of elements in the collection is:" + c.size()); // 0 // Then add elements to the collection c.add("hello"); // The memory address of the "hello" object is placed in the collection. c.add("world"); c.add("hulk "); c.add("The Incredible Hulk"); c.add(1); // Judge whether the collection contains "Hulk" boolean flag = c.contains("The Incredible Hulk"); System.out.println(flag); // true boolean flag2 = c.contains("Hulk 2"); System.out.println(flag2); // false System.out.println(c.contains(1)); // true System.out.println("The number of elements in the collection is:" + c.size()); // 5 // Delete an element in the collection c.remove(1); System.out.println("The number of elements in the collection is:" + c.size()); // 4 // Judge whether the collection is empty (whether there are elements in the collection) System.out.println(c.isEmpty()); // false // empty c.clear(); System.out.println(c.isEmpty()); // True (true means there are no elements in the collection!) c.add("abc"); c.add("def"); c.add(100); c.add("helloworld!"); c.add(new Student()); // Convert to array (understand, not used much.) Object[] objs = c.toArray(); for(int i = 0; i < objs.length; i++){ // Traversal array Object o = objs[i]; System.out.println(o); } } } class Student{ }
Drill down into the contains method in the Collection
Note: in the same way as the remove method, the underlying layer calls the equals method
import java.util.ArrayList; import java.util.Collection; /* Delve into the contains method of the Collection: boolean contains(Object o) Determine whether the collection contains an object o Returns true if included and false if not included. contains Method is a method used to determine whether a collection contains an element, So how does it determine whether a collection contains an element at the bottom? The equals method was called for comparison. equals Method returns true, indicating that the element is included. */ public class CollectionTest04 { public static void main(String[] args) { // Create collection object Collection c = new ArrayList(); // Storing elements into a collection String s1 = new String("abc"); // s1 = 0x1111 c.add(s1); // Put in an "abc" String s2 = new String("def"); // s2 = 0x2222 c.add(s2); // Number of elements in the collection System.out.println("The number of elements is:" + c.size()); // 2 // New object String String x = new String("abc"); // x = 0x5555 // Does the c set contain x? Guess whether it's true or false? System.out.println(c.contains(x)); //Judge whether there is "abc" true in the collection } }
The third key point: understand the iterator.
During the use of iterator, the original set cannot be changed, otherwise an exception will occur
Iterator traverses ArrayList
/** * Topics on set traversal / iteration. (key points: five stars * * * *) */ public class CollectionTest02 { public static void main(String[] args) { // Note: the traversal / iteration method explained below is a common method for all collections. // Cannot be used in Map Collection. Used in all collections and subclasses. // Create collection object Collection c = new ArrayList(); // The later Collection doesn't matter. It mainly depends on how the previous Collection interface traverses / iterates. // Add element c.add("abc"); c.add("def"); c.add(100); c.add(new Object()); // Traverse / iterate over the Collection // Step 1: get the Iterator object Iterator of the collection object Iterator it = c.iterator(); // Step 2: start iterating / traversing the collection through the iterator object obtained above. /* The following two methods are methods in the Iterator object Iterator: boolean hasNext()Returns true if there are still elements to iterate over. Object next() Returns the next element of the iteration. */ while(it.hasNext()){ Object obj = it.next(); System.out.println(obj); } // If you keep fetching and don't judge, an exception will appear: java.util.NoSuchElementException /*while(true){ Object obj = it.next(); System.out.println(obj); }*/ /*boolean hasNext = it.hasNext(); System.out.println(hasNext); if(hasNext) { // No matter what you put in at the beginning, it is an Object when you take it out. Object obj = it.next(); System.out.println(obj); } hasNext = it.hasNext(); System.out.println(hasNext); if(hasNext) { Object obj = it.next(); System.out.println(obj); } hasNext = it.hasNext(); System.out.println(hasNext); if(hasNext) { Object obj = it.next(); System.out.println(obj); } hasNext = it.hasNext(); System.out.println(hasNext); if(hasNext) { Object obj = it.next(); System.out.println(obj); } hasNext = it.hasNext(); System.out.println(hasNext); if(hasNext) { Object obj = it.next(); System.out.println(obj); }*/ } }
Iterator traverses HashSet and ArrayList
import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; /* On iteration / traversal of sets */ public class CollectionTest03 { public static void main(String[] args) { // Create collection object Collection c1 = new ArrayList(); // ArrayList set: ordered and repeatable // Add element c1.add(1); c1.add(2); c1.add(3); c1.add(4); c1.add(1); // Iterative set Iterator it = c1.iterator(); while(it.hasNext()){ // What is the type of deposit and what is the type of withdrawal. Object obj = it.next(); /*if(obj instanceof Integer){ System.out.println("Integer Type ""); }*/ // But it will be converted into a string when outputting, because println will call the toString() method here. System.out.println(obj); } // HashSet set: unordered and non repeatable Collection c2 = new HashSet(); // Disorder: the order of saving and taking out is not necessarily the same. // Non repeatable: store 100, no more 100 c2.add(100); c2.add(200); c2.add(300); c2.add(90); c2.add(400); c2.add(50); c2.add(60); c2.add(100); Iterator it2 = c2.iterator(); while(it2.hasNext()){ System.out.println(it2.next()); } } }
The fourth key point: the bottom layer of the remove method and the contains method in the Collection interface will call equals,
Find out.
1. Common methods in the List interface.
List is a sub interface of the Collection interface. Therefore, there are some unique methods in the list interface.
void add(int index, Object element)
Object set(int index, Object element)
Object get(int index)
int indexOf(Object o)
int lastIndexOf(Object o)
Object remove(int index)
2. The remove method of the collection object cannot be used to delete an element when the iterator iterates over the element,
To use the remove method of the Iterator iterator to delete elements and prevent exceptions:
ConcurrentModificationException
3,ArrayList
ArrayList collection initialization capacity 10
The capacity expansion is 1.5 times of the original capacity.
Bitwise operation old length + old moves one bit to the right, so it is 1.5 times the capacity expansion
The bottom layer is an array.
Array advantages and disadvantages should be able to say!
ArrayList randomly adds and deletes elements with low efficiency and high query efficiency!
Also note: adding and deleting elements at the end of the ArrayList set is efficient.
4. Linked list data structure
First: the data structure of one-way linked list and two-way linked list should be understood.
Second: the advantages and disadvantages of linked list data structure should be able to say.
High efficiency of random addition and deletion of elements! Low query efficiency 1
5,Vector:
Vector initialization capacity is 10
The expansion capacity is twice the original capacity.
The bottom layer is an array.
The underlying layer of Vector is thread safe.
How to get a thread safe List:
Collections.synchronizedList(list);
6. What's new in JDK 5.0: generics
First: collections use generics to reduce downward transformation operations.
Second: how to use generics?
Third: how to customize generics?
7. New features of JDK5.0:
foreach
How to traverse an array?
for(int i : arr){
System.out.println(i);
}
How to traverse the collection?
for(String s : list){
System.out.println(s);
}
8. New feature of JDK8: Diamond expression
List list = new ArrayList<>();
Type auto inference!
1. Master common methods in Map interface.
put method
import java.util.HashSet; import java.util.Set; /* 1,The hashCode method of the key is called first, and then the equals method is called when saving to and fetching from the Map collection! equals Methods may or may not be called. Take put(k,v) as an example. When will equals not be called? k.hashCode()Method returns a hash value, The hash value is converted into an array subscript by a hash algorithm. If the array subscript position is null, equals does not need to be executed. Take get(k) as an example. When will equals not be called? k.hashCode()Method returns a hash value, The hash value is converted into an array subscript by a hash algorithm. If the array subscript position is null, equals does not need to be executed. 2,Note: if the equals method of a class is overridden, the hashCode() method must be overridden. And if the equals method returns true, the value returned by the hashCode() method must be the same. equals Method returns true, indicating that the two objects are the same and are compared on the same one-way linked list. Then, for the nodes on the same one-way linked list, their hash values are the same. Therefore, the return value of the hashCode() method should also be the same. 3,hashCode()Methods and equals() methods need not be studied. They are generated directly by the IDEA tool, but these two methods need to be generated at the same time. 4,Final conclusion: The elements placed in the key part of the HashMap set and the elements placed in the HashSet set need to override both the hashCode method and the equals method. 5,For hash table data structures: If the hash values of o1 and o2 are the same, they must be placed on the same one-way linked list. Of course, if the hash values of o1 and o2 are different, but the array subscripts converted after the execution of the hash algorithm may be the same, a "hash collision" will occur. */ public class HashMapTest02 { public static void main(String[] args) { Student s1 = new Student("zhangsan"); Student s2 = new Student("zhangsan"); // false before overriding the equals method //System.out.println(s1.equals(s2)); // false // true after overriding the equals method System.out.println(s1.equals(s2)); //true (s1 and s2 mean equal) System.out.println("s1 of hashCode=" + s1.hashCode()); //284720968 (after rewriting hashCode - 1432604525) System.out.println("s2 of hashCode=" + s2.hashCode()); //122883338 (after rewriting hashCode - 1432604525) // The result of s1.equals(s2) is true, which means that s1 and s2 are the same. If you put them into the HashSet set, // Normally, only one can be put in. (HashSet set features: unordered and unrepeatable) Set<Student> students = new HashSet<>(); students.add(s1); students.add(s2); System.out.println(students.size()); // Normally, the result should be 1. But the result is 2. Obviously, it does not meet the storage characteristics of HashSet collection. What should I do? } }
size method
get method
map.entrySet() method
2. You should be proficient in both ways of traversing Map sets.
The first method: obtain all keys, traverse each key, and obtain value through key
The second method: get Set < map. Entry > and traverse the entries in the Set
Call entry.getKey() entry.getValue()
3. Understand the hash table data structure.
4. The elements stored in the key part of the HashMap set and the HashSet set set need to rewrite hashCode and equals at the same time.
5. The difference between HashMap and Hashtable.
HashMap:
The initialization capacity is 16 and the expansion capacity is 2 times.
Non thread safe
key and value can be null.
Hashtable
Initialization capacity 11, capacity expansion 2x + 1
Thread safety
Neither key nor value can be null.
6. There are two common methods of the Properties class.
setProperty
getProperty
7. Understand the data structure of self balanced binary tree.
Left small right large principle storage.
Middle order traversal mode.
8. There are two ways to sort the key of TreeMap or the elements in TreeSet collection:
The first is to implement the java.lang.Comparable interface.
Second: write a Comparator interface separately.
9. Collection tool class Collections:
synchronizedList method
sort method (requires the elements in the collection to implement the Comparable interface.)
1. What is the main content of the collection?
1.1. Creation of each collection object (new)
1.2. Add elements to the set
1.3. Extract an element from the set
1.4. Traversing the set
1.5. Main collection classes:
ArrayList
/* 1.1,Creation of each collection object (new) 1.2,Add elements to the collection 1.3,Take an element from the collection 1.4,Traversal set */ public class ArrayListTest { public static void main(String[] args) { // Create collection object //ArrayList<String> list = new ArrayList<>(); LinkedList<String> list = new LinkedList<>(); // Add element list.add("zhangsan"); list.add("lisi"); list.add("wangwu"); // Take an element from the collection // The List collection has subscripts String firstElt = list.get(0); System.out.println(firstElt); // Traversal (subscript mode) for(int i = 0; i < list.size(); i++){ String elt = list.get(i); System.out.println(elt); } // Traversal (iterator mode, which is universal and can be used by all collections) Iterator<String> it = list.iterator(); while(it.hasNext()){ System.out.println(it.next()); } // Change the while loop to a for loop /*for(Iterator<String> it2 = list.iterator(); it2.hasNext(); ){ System.out.println("====>" + it2.next()); }*/ // Traversal (foreach mode) for(String s : list){ System.out.println(s); } } }
LinkedList
HashSet (the key of HashMap, and the elements stored in the key of HashMap set need to rewrite hashcode + equals at the same time)
/* 1.1,Creation of each collection object (new) 1.2,Add elements to the collection 1.3,Take an element from the collection 1.4,Traversal set 1.5,Test the characteristics of HashSet set: unordered and unrepeatable. */ public class HashSetTest { public static void main(String[] args) { // Create collection object HashSet<String> set = new HashSet<>(); // Add element set.add("abc"); set.add("def"); set.add("king"); // Elements in the set set cannot be retrieved by subscript. There is no subscript // Traversal collection (iterator) Iterator<String> it = set.iterator(); while(it.hasNext()){ System.out.println(it.next()); } // Traversal set (foreach) for(String s : set){ System.out.println(s); } set.add("king"); set.add("king"); set.add("king"); System.out.println(set.size()); //3 (the last three king s are not added.) set.add("1"); set.add("10"); set.add("2"); for(String s : set){ System.out.println("--->" + s); } // Create a Set set to store Student data Set<Student> students = new HashSet<>(); Student s1 = new Student(111, "zhangsan"); Student s2 = new Student(222, "lisi"); Student s3 = new Student(111, "zhangsan"); students.add(s1); students.add(s2); students.add(s3); System.out.println(students.size()); // 2 // ergodic for(Student stu : students){ System.out.println(stu); } } } class Student { int no; String name; public Student() { } public Student(int no, String name) { this.no = no; this.name = name; } @Override public String toString() { return "Student{" + "no=" + no + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student student = (Student) o; return no == student.no && Objects.equals(name, student.name); } @Override public int hashCode() { return Objects.hash(no, name); } }
TreeSet
/* 1.1,Creation of each collection object (new) 1.2,Add elements to the collection 1.3,Take an element from the collection 1.4,Traversal set 1.5,Test that the elements in the TreeSet collection are sortable. 1.6,The types stored in the test TreeSet collection are custom. 1.7,Test the way to implement the Comparable interface 1.8,Test the way to implement the Comparator interface (it is best to test the following anonymous inner classes) */ public class TreeSetTest { public static void main(String[] args) { // Collection creation (you can test the storage of String and Integer in the following TreeSet collection. These classes are written by SUN.) //TreeSet<Integer> ts = new TreeSet<>(); // Writing a comparator can change the rules. TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; // Automatic unpacking } }); // Add element ts.add(1); ts.add(100); ts.add(10); ts.add(10); ts.add(10); ts.add(10); ts.add(0); // Traversal (iterator mode) Iterator<Integer> it = ts.iterator(); while(it.hasNext()) { Integer i = it.next(); System.out.println(i); } // Traversal (foreach) for(Integer x : ts){ System.out.println(x); } // Store custom types in the TreeSet collection TreeSet<A> atree = new TreeSet<>(); atree.add(new A(100)); atree.add(new A(200)); atree.add(new A(500)); atree.add(new A(300)); atree.add(new A(400)); atree.add(new A(1000)); // ergodic for(A a : atree){ System.out.println(a); } //TreeSet<B> btree = new TreeSet<>(new BComparator()); // Anonymous inner class method. TreeSet<B> btree = new TreeSet<>(new Comparator<B>() { @Override public int compare(B o1, B o2) { return o1.i - o2.i; } }); btree.add(new B(500)); btree.add(new B(100)); btree.add(new B(200)); btree.add(new B(600)); btree.add(new B(300)); btree.add(new B(50)); for(B b : btree){ System.out.println(b); } } } // The first method: implement the Comparable interface class A implements Comparable<A>{ int i; public A(int i){ this.i = i; } @Override public String toString() { return "A{" + "i=" + i + '}'; } @Override public int compareTo(A o) { //return this.i - o.i; return o.i - this.i; } } class B { int i; public B(int i){ this.i = i; } @Override public String toString() { return "B{" + "i=" + i + '}'; } } // comparator class BComparator implements Comparator<B> { @Override public int compare(B o1, B o2) { return o1.i - o2.i; } }
HashMap
/* 1.1,Creation of each collection object (new) 1.2,Add elements to the collection 1.3,Take an element from the collection 1.4,Traversal set */ public class HashMapTest { public static void main(String[] args) { // Create a Map collection Map<Integer, String> map = new HashMap<>(); // Add element map.put(1, "zhangsan"); map.put(9, "lisi"); map.put(10, "wangwu"); map.put(2, "king"); map.put(2, "simth"); // If the key is repeated, the value will be overwritten. // Get the number of elements System.out.println(map.size()); // Take the element whose key is 2 System.out.println(map.get(2)); // smith // It is very important to traverse the Map set in several ways. // The first method: get all the keys first. When traversing the keys, get the value through the key Set<Integer> keys = map.keySet(); for(Integer key : keys){ System.out.println(key + "=" + map.get(key)); } // The second method is to convert a Map Set into a Set set. Each element in the Set set is a Node // This Node contains key and value Set<Map.Entry<Integer,String>> nodes = map.entrySet(); for(Map.Entry<Integer,String> node : nodes){ System.out.println(node.getKey() + "=" + node.getValue()); } } }
Properties
TreeMap