1, Collection overview
1. Definitions
Combination is actually a container. Can be used to accommodate other types of data.
2. Set discrimination
Collections cannot directly store basic data types. In addition, collections cannot directly store java objects. The memory addresses of java objects are stored in collections. (or the collection stores references.)
list.add(100); //Autoboxing Integer
3. Under which JDK package is the collection located?
java.util.*;
All collection classes and collection interfaces are under the java.util package.
4. Set classification
One is to store elements in a single way. The super parent interface in this kind of collection: java.util.Collection;
One is to store elements in the form of key value pairs. The super parent interface in this class collection: java.util.Map;
5. Three main types of sets
List: it is an ordered collection that can put duplicate data.
Set: an unordered set. Duplicate data is not allowed.
Map: it is an unordered collection. The collection contains a key object and a value object. The key object cannot be repeated, and the value object can be repeated.
6. Set inheritance structure diagram
-
collection section
-
Map section
-
Summary
2, Collection and Iterator
1. Collection is the parent interface of List and Set. Some main methods are defined in collection
add();//Ensure that this collection contains the specified element addAll();//Adds all elements in the specified collection to this collection clear();//Remove all elements in this collection contains();//Returns true if the collection contains the specified element equals();//Compares whether this collection is equal to the specified object hashCode();//Returns the hash code value of this collection isEmpty();//Returns true if this collection does not contain elements iterator();//Returns the iterator that iterates over the elements of this collection remove();//Removes a single instance of the specified element from this collection size(); //Returns the number of elements in this collection toArray();//Returns an array containing all elements in this collection
2. Iterator is called iterative interface, through which you can traverse the data in the collection. The main methods of this interface are
hashNext();//Returns true if there are still elements to iterate over next();//Returns the next element of the iteration
The remove method of the collection object cannot be used to delete elements during the Iterator's iteration of elements. The remove method of the Iterator should be used to delete elements to prevent exceptions: ConcurrentModificationException
3, List interface
1. General
There are two main implementations of ArrayList and LinkedList under the List interface. They are based on linear storage (what order to store, what order to take out or what order), and can be regarded as a variable array.
2. Introduction to four implementations
ArrayList: querying data is fast and adding and deleting data is slow (based on variable array). The initialization capacity is 10, and the expansion capacity is 1.5 times of the original capacity.
LinkedList: it is slow to query data and fast to add and delete data (based on the linked list data structure).
Vector: it is no longer recommended. The methods in vector are synchronous and slow. They have been replaced by ArrayList. The initialization capacity of vector is 10, and the expansion capacity is twice the original capacity. The bottom layer is an array. The underlying layer of vector is thread safe.
Stack inherits Vector and implements a stack. The stack structure is last in first out. At present, it has been replaced by LinkedList.
3. Common methods
//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);
4. How to get a thread safe List
Collections.synchronizedList(list);
5. Syntax format
//It's better not to write like this. It belongs to concrete oriented programming //Cannot achieve flexible interchange //Interface oriented programming is preferred ArrayList arrayList = new ArrayList(); //Interface oriented programming //Using Collection will be more flexible if the List cannot meet the requirements //You can use HashSet because HashSet also implements this interface Collection c = new ArrayList(); //Interface oriented programming //Using the list interface, you can use the methods in the Collection //You can also use the list interface extension method List l = new ArrayList(); //The usage of LinkedList is the same as above Collection c = new LinkedList(); List l = new LinkedList();
4, forEach
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); }
5, Set interface
1. HashSet
The data in the HashSet is unordered and non repeatable. HashSet accesses data according to the hash algorithm and has very good performance. Its working principle is as follows. When inserting data into HashSet, it will call the hashCode of the object to get the hash code of the object, and then calculate the position of the object inserted into the set according to the hash code.
Set set = new HashSet(); set.add("a"); set.add("b"); set.add("c"); //The output is out of order for (Iterator it = set.iterator(); it.hasNext();) { System.out.println(it.next()); }
2. equals() and hashCode() methods
Specify in Java:
- If two objects have equal equals, their hashcode is equal.
- If the equals of two objects are not equal, its hashcode does not require it to be equal, but it is generally recommended not to be equal
- hashcode equality does not mean that two objects are equal (using equals comparison)
Therefore, when adding data to HashSet or HashMap, the equals and hashCode methods must be overwritten at the same time, because the rewritten equals method must ensure that the same two objects have the same hash value. The rewriting principle of the hashCode method is to ensure that two objects identified by the equals method as the same have the same hash value.
3. TreeSet
TreeSet can sort Set sets by default, which is natural sorting (i.e. ascending), but it can also be customized. Similarly, duplicate data cannot be placed. Sorting can only sort one type.
Set set = new TreeSet(); set.add(9); set.add(2); set.add(5); set.add(1);//The input data will be sorted in ascending order
4. User defined sorting rules
- Implement the Comparable interface to complete sorting
For example:
class Person implements Comparable { String name; int age; //If equals is overridden, it is best to ensure that equals and compareto are //The comparison rules in the case of equality are consistent public int compareTo(Object o) { if (o instanceof Person) { Person p = (Person)o; //Ascending order //return (this.age - p.age); //Descending order return (p.age-this.age); } throw new IllegalArgumentException("Illegal parameter, o=" + o); }
- Implement the Comparator interface to complete sorting
//Comparator for implementing Person //What is the difference between Comparator and Comparable? //Comparable is the default comparison interface. It is closely combined with the objects to be compared Yes //Comparator can separate comparison rules, so it is more flexible class PersonComparator implements Comparator { public int compare(Object o1, Object o2) { if (!(o1 instanceof Person)) { throw new IllegalArgumentException("Illegal parameter, o1=" + o1); } if (!(o2 instanceof Person)) { throw new IllegalArgumentException("Illegal parameter, o2=" + o2); } Person p1 = (Person)o1; Person p2 = (Person)o2; return p1.age - p2.age; } }
- Anonymous inner class writing
Set set = new TreeSet(new Comparator() { public int compare(Object o1, Object o2) { if (!(o1 instanceof Person)) { throw new IllegalArgumentException("Illegal parameter, o1=" + o1); } if (!(o2 instanceof Person)) { throw new IllegalArgumentException("Illegal parameter, o2=" + o2); } Person p1 = (Person)o1; Person p2 = (Person)o2; return p1.age - p2.age; } });
- The difference between Comparable and Comparator
If a class implements the Camparable interface, it indicates that the objects of this class can be compared with each other, and the collection composed of this class object can be sorted directly by the sort method.
Comparator can be regarded as an implementation of algorithm, separating algorithm and data. Comparator can also be used in the following two environments:
1. Class does not consider the comparison problem and does not implement Comparable. Sorting can be realized through Comparator without changing the object itself.
2. You can use a variety of sorting criteria, such as ascending and descending.
6, Map interface
1. General
Key value pairs can be placed in the Map, that is, each element contains key objects and value objects. The most commonly used Map implementation is HashMap. HashMap still uses hash algorithm to access key objects like HashSet. Therefore, if you use a self-defined class as the key object of the Map, you must copy the equals and hashCode methods.
2. HashMap
The backbone of HashMap is an entry array. Entry is the basic unit of HashMap. Each entry contains a key value pair. (in fact, the so-called Map is actually a collection that saves the mapping relationship between two objects).
- common method
1.put(K key, V value) Will key( key)/Value( value)Map to Map In collection. 2.get(Object key) Returns the value mapped by the specified key. There is no such value key The corresponding value is returned null. 3.size() return Map Number of data in the collection. 4.clear() empty Map aggregate 5.isEmpty () judge Map Whether there is data in the collection. If not, it returns true,Otherwise return false. 6.remove(Object key) delete Map The key in the collection is key And return the corresponding data value value. 7.values() return Map All in the collection value Composed of Collection Data type format data. 8.entrySet() take Map Set each key-value Convert to a Entry Object and returns all Entry Object composition Set aggregate.
- Two methods of traversing Map set
The first method: obtain all keys, traverse each key, and obtain value through key
The second method: just get Set < map. Entry >, traverse the entries in the Set, and call entry. Getkey(), entry. Getvalue()
The second detailed explanation:
Set<Map.Entry<Integer, String>> set = studentMap.entrySet(); for (Map.Entry<Integer, String> entry : set) { String key = entry.getKey(); String value = entry.getValue(); System.out.println(key+":"+value); }
The elements stored in the key part of the HashMap set and the HashSet set set need to override the hashCode and equals methods at the same time.
3. HashTable
- Introduction to HashTable
Hashtable is also implemented based on hash table. Similarly, each element is a key value pair, and its internal conflict is solved through single linked list. The capacity is insufficient (exceeding the threshold) Hashtable is also a class introduced by JDK1.0. It is thread safe and can be used in multi-threaded environment. Hashtable also implements the Serializable interface, supports serialization, implements the clonable interface and can be cloned.
- Differences between HashTable and HashMap
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.
4. Properties
- brief introduction
This class is mainly used to read Java configuration files. Different programming languages have their own supported configuration files. Many variables in the configuration file are often changed. In order to facilitate user configuration, users can modify relevant variable settings without the program itself. Just like in Java, its configuration file is often a. Properties file, which configures parameters in the form of key value pairs , which is a subclass of the Hashtable collection and is also thread safe. The properties class represents a persistent property set. Properties can be saved in or loaded from the stream. Each key and its corresponding value in the property list are a string.
- common method
getProperty(String key);//Search for attributes in this attribute list with the specified key. setProperty(String key, String value);//Call the put method of Hashtable.
5. TreeMap
- brief introduction
TreeMap can sort the keys in the map. If the keys in the map adopt self-defined classes, you need to implement the Comaprable or Comparator interface to complete the sorting
- The difference and relation between TreeMap and TreeSet
Similarities:
TreeMap and TreeSet are ordered collections, that is, the values they store are ordered.
Both TreeMap and TreeSet are asynchronous collections, so they cannot be shared among multiple threads, but they can be synchronized using the method collections. Synchronizedmap().
The running speed is slower than the Hash set. The internal operation time complexity of elements is O(logN), while the HashMap/HashSet is O(1).
difference:
The main difference is that TreeSet and TreeMap implement Set and Map interfaces respectively
TreeSet stores only one object, while TreeMap stores two objects, key and Value (only key objects are ordered)
Duplicate objects cannot exist in TreeSet, but can exist in TreeMap
The bottom layer of TreeMap adopts the implementation of red black tree to complete the orderly insertion and sorting of data.
7, Collection tool class collections
- common method
void reverse(List list): reversal void shuffle(List list),Random sorting void sort(List list),Sort in ascending natural order void sort(List list, Comparator c);Custom sorting by Comparator Control sort logic void swap(List list, int i , int j),Swap elements at two index positions void rotate(List list, int distance),Rotate. When distance When positive, the list after distance Move the whole element to the front distance When it is negative, the list Before distance Move the whole element to the back. void synchronizedList(List list);take list Set to thread safe.
8, Generics
- definition
Java generics is a new feature introduced in JDK 5. Generics provides a compile time type safety detection mechanism, which allows programmers to detect illegal types at compile time. The essence of generics is parameterized types, that is, the data type operated is specified as a parameter.
Suppose we have such a requirement: write a sorting method that can sort integer arrays, string arrays or even any other type of arrays. How to implement it? The answer is that Java generics can be used.
Using the concept of Java generics, we can write a generic method to sort an array of objects. Then we call this generic method to sort integer arrays, floating point arrays, and string arrays.
- Syntax format
ArrayList<String> stringValues=new ArrayList<String>();
- Instantiation of generics
List<String> strList = new ArrayList<String>();//Specify the value (type) of the type parameter after the class name
- Diamond expression
List<String> list = new ArrayList<>();//Automatic type inference will infer what type is in < >, based on the generic type of the previously compiled type