Java Collection knowledge point summary-blog Park: Holding, holding, java knowledge point
Differences between arrays and collections:
Arrays in Java are collections that store the same type of data. An array can store basic data or referenced data, but the length of the array is fixed.
A set can only store referenced data types, but cannot store basic data types, but the number of sets is variable.
All collection classes are stored in the java. util package.
The List interface is a set of elements in order and can be repeated. You must override the equals () method when adding a custom class.
In the ArrayList set, when an element is inserted, the list needs to move all elements after the inserted point backward, while When deleting (remove () an element, move all elements after the deleted element forward
The ArrayList set allows all elements, including null.
Example 1: some basic methods of ArrayList
Public class ArrayListText {
Public static void main (String [] args ){
Collection <String> collection = new ArrayList <String> ();
List <String> list = new ArrayList <String> ();
Collection. add ("1 ");
Collection. add ("2 ");
Collection. add ("3 ");
List. add ("");
List. add ("B ");
List. add ("C ");
List. addAll (0, collection); // Add all elements of a set to a specified position
System. out. println ("list set:" + list );
List <String> subList = list. subList (1, 5 );
System. out. println ("subList set:" + subList );
System. out. println ("before setting the elements of the list set:" + list. get (3 ));
List. set (3, "Set ");
System. out. println ("after setting the list set element:" + list. get (3 ));
System. out. println ("position of element 3 in list set:" + list. indexOf ("3") + ", location of Element D:" + list. indexOf ("D"); // obtain the index position of the specified Element in the set. If no index exists,-1 is returned.
String arrString [] = list. toArray (new String [] {}); // convert the set into a String Array
For (String str: arrString ){
System. out. print (str + "");
}
System. out. println ("\ nlist set empty:" + list. isEmpty ());
List. clear ();
System. out. println ("\ nlist set empty:" + list. isEmpty ());
}
}
Result:
List set: [1, 2, 3, A, B, C]
SubList set: [2, 3, A, B]
Before setting the list set elements:
After setting the list Set element: Set
In the list set, the position of element 3 is 2, and the position of Element D is-1.
1 2 3 Set B C
Empty list set: false
Empty list set: true
Converts an array to an ArrayList set.
String [] str = {"W", "E", "C", "O", "M", "E "};
List <String> list = Arrays. asList (str );
ArrayList <String> arrList = new ArrayList <String> ();
ArrList. addAll (list );
A linked list is a linked list type. The structure of a linked list facilitates the insertion and deletion of elements to a set. Because no elements need to be moved when an element is inserted or deleted, the exist list can also have a null element.
How to obtain the table header:
GetFirst (): only get the Header element (): Get but not remove this chain table header peek (): Get but not remove this chain table header poll (): get and remove this linked list header pop (): Get and remove this linked list Header
Example 2: Getting linked list Headers
Public class implements listtext {
Public static void main (String [] args ){
Shortlist <String> link = new shortlist <String> ();
Link. add ("1 ");
Link. add ("2 ");
Link. add ("3 ");
Link. addFirst ("F ");
Link. addLast ("L ");
Shortlist <String> newLink = new shortlist <String> (link );
System. out. println ("add element: \ n \ t" + link );
System. out. println ("get () method to obtain the header:" + link. getFirst ());
System. out. println ("after the get () method is used: \ n \ t" + link );
System. out. println ("element () method to obtain the header:" + link. element ());
System. out. println ("after using the element () method: \ n \ t" + link );
System. out. println ("peek () method to obtain the header:" + link. peek ());
System. out. println ("after using the peek () method: \ n \ t" + link );
System. out. println ("poll () method to obtain the header:" + link. poll ());
System. out. println ("after using the poll () method: \ n \ t" + link );
System. out. println ("pop () method to obtain the header:" + link. pop ());
System. out. println ("after the pop () method is used: \ n \ t" + link );
System. out. println ("******* use the linked list first-in-first-out *******");
Int len = newLink. size ();
For (int I = 0; I <len; I ++ ){
System. out. print (newLink. poll () + "");
}
}
}
Result:
After adding the element:
[F, 1, 2, 3, L]
Get () method to get the header: F
After the get () method is used:
[F, 1, 2, 3, L]
Element () method to obtain the header: F
After using the element () method:
[F, 1, 2, 3, L]
Obtain the table header using the peek () method: F
After using the peek () method:
[F, 1, 2, 3, L]
Poll () method to obtain the header: F
After using the poll () method:
[1, 2, 3, L]
The pop () method obtains the header: 1
After the pop () method is used:
[2, 3, L]
* ***** Use the linked list first-in-first-out *****
F 1 2 3 L
The Set is a Set of unordered elements that cannot be repeated. It can contain null elements. To add a custom class, you must override the equals () and hashcode () methods.
The HashSet class can quickly locate an element, but the elements in the HashSet set must overwrite the equals () and hashcode () methods, while the TreeSet set class stores the elements in it in order.
HashSet stores elements in a set based on the hash algorithm, and uses the hash algorithm to improve access efficiency.
Features of a HashSet set: 1. the arrangement order of elements cannot be guaranteed. The order of elements in the set may change at any time. A maximum of three null elements can exist in a collection. the HashSet set is not synchronized by threads.
The insertion performance of LinkedHashSet is slightly lower than that of HashSet, but it has good performance in iterative access to all the elements in the Set. LinkedHashSet () maintains the order of adding the elements to the Set using the linked list, as a result, when we traverse the elements of the javashashset set, we traverse the elements in the order of addition, but it cannot be said that it is orderly!
The TreeSet class implements the Set interface and SortedSet interface in the java. util package. The elements in the TreeSet Set are sorted in ascending order by default.
Features of the TreeSet set: 1. the elements added to the TreeSet must be of the same class. traverse from small to large 3. when the custom class does not implement the Comparable interface, an error is returned when this object is added to the TreeSet.
Example 2: Customize the class to implement the Comparable Interface
Class Person implements Comparable {
Private String name;
Private String age;
Public Person (){
}
Public Person (String name, int age ){
This. name = name;
This. age = age;
}
Public int compareTo (Person per ){
If (this. age> per. age ){
Return 1;
} Else if (this. age <per. age ){
Return-1;
} Else {
Return this. name. compareTo (per. name );
}
}
Public String toString (){
Return ("name:" + name + ", age:" + age + "\ n ");
}
}
Public class TreeSetDemo {
Public static void main (String [] args ){
Set <Person> tset = new TreeSet <Person> ();
Tset. add (new Person ("Xiaoqiang", 21 ));
Tset. add (new Person ("Xiaowei", 23 ));
Tset. add (new Person ("Xiaoqiang", 21 ));
Tset. add (new Person ("Xiaoqiang", 21 ));
Tset. add (new Person ("xiaoqin", 20 ));
Tset. add (new Person ("xiaoting", 20 ));
System. out. println (tset );
}
}
Result:
[Name: xiaoting, age: 20
, Name: xiaoqin, age: 20
, Name: Xiaoqiang, age: 21
, Name: Xiao Wei, age: 23
]
Set output: 1. Iterator: Iterator output (provides Iterator for Traversing various set types) 2. foreach: JDK1.5 new output
Iterative deletion:
Iterator <String> it = link. iterator ();
While (it. hasNext ){
It. next ();
It. remove ();
}
Note: Before calling the remove () method, you must use the next () method to specify the element to be deleted. Otherwise, an IllegalStateException exception will occur during running.
The Map interface provides key-value ing, where keys cannot be repeated. Each key can only Map one value, and the String class is commonly used as the Map key.
A key-value pair is an Entry. All entries are stored in Set and cannot be repeated. Keys are stored in Set and cannot be repeated. Values are stored in Collection and can be repeated.
The Map. Entry interface is static, so it can be called directly in the form of "external class. Internal class"
The HashMap class is a set of Map functions. It is highly efficient to add and delete elements. The HashMap class provides all the optional ing operations and allows the use of null values and null keys. However, the key must be unique and the HashMap class is non-synchronous and does not guarantee the ing sequence.
Example 3: obtain all keys and values in the Map set.
Public class HashMapDemo {
Public static void main (String [] arg ){
Map <Integer, String> map = new HashMap <Integet, String> ();
Map. put (1, "Tsinghua University ");
Map. put (2, "Peking University ");
Map. put (3, "Fudan University ");
Map. put (4, "Wuhan University ");
Map. put (5, "Emy of Science and Technology ");
Map. put (6, "China University of Mining and Technology ");
Set <Integer> set = map. keySet ();
Iterator <Integet> itKey = set. iterator ();
System. out. println ("all keys in the Map set :");
While (itKey. hasNext ()){
System. out. print (itKey. next () + "");
}
System. out. println ();
Collection <String> c = map. values ();
Iterator <String> itValue = c. iterator ();
System. out. println ("all values in the Map set :");
While (itValue. hasNext ()){
System. out. print (itValue. next () + "");
}
}
}
Result:
All keys in the Map set:
1 2 3 4 5 6
All values in the Map set:
Tsinghua University Peking University Fudan University Wuhan University of Science and Technology China miners' University
Example 4: Use Iterator to output a Map set
Public class hashMapDemo {
Public static void main (String [] args ){
Map <Integer, String> map = new HashMap <Integet, String> ();
Map. put (1, "Tsinghua University ");
Map. put (2, "Peking University ");
Map. put (3, "Fudan University ");
Map. put (4, "Wuhan University ");
Map. put (5, "Emy of Science and Technology ");
Map. put (6, "China University of Mining and Technology ");
Set <Map. Entry <Integer, String> set = map. entrySet ();
Iterator <Map. Entry <Integet, String> it = set. iterator ();
System. out. println ("Key -------- Value ");
While (it. hasNext ()){
Map. Entry <Integer, String> mapEntry = it. next ();
System. out. println ("" + mapEntry. getKey () + "-------" + mapEntry. getValue ());
}
}
}
Result:
Key ------ value
1 ----- Tsinghua University
2 ----- Peking University
3 ----- Fudan University
4 ----- Wuhan University
5 ----- China University of Science and Technology
6 ----- China University of Mining and Technology
Use foreach output:
For (Map. Entry <Integet, String> mapEntry: map. entryKey ()){
System. out. println ("" + mapEntry. getKey () + "-------" + mapEntry. getValue ());
}
The TreeMap class not only implements the Map interface, but also the SortedMap interface. Therefore, the ing relationships in the TreeMap set are sequential. Compared with HashMap, The TreeMap set has low performance in adding, deleting, and locating elements.
The Collections class can sort, reverse, extreme values, cyclic shift, query, and modify the elements of a set, you can also set the collection object to be immutable and implement synchronization control on the collection object.
The methods provided by the Collections class are static methods, which can be called directly in the form of "class name. Method ()".
Common Methods of Collections: addAll (Collection c, T... elements) -- Collections. addAll (list, "1", "2", "3") binarySearch (List list, T key)-before using this method, you must first use sort (List list, Comparator c) copy (List dest, List src) // copy all elements in the src set to fill (List list List, T obj) in the dest set) // use the specified element to replace all elements in the specified set with max (Collection coll) max (Collection coll, Comparator c) replaceAll (List list, T oldVal, T newVal) // use another element to replace all the specified elements in the set. reverse (List list)
Stack-Stack is a special linear table. It is limited to adding and deleting elements at the end of the table. The end of the stack table becomes the top of the stack, and the header becomes the bottom of the stack. Stack is a data storage method that uses "advanced and later". If the stack does not contain any elements, it becomes an empty stack. Stack is a subclass of Vector
Empty () // determines whether the stack is empty. If it is empty, true peek () is returned // gets the top element of the stack, but does not delete it pop () // gets the top element of the stack, and delete it push () // Add the element to the top of the stack search (), find the position of the specified Element in the stack, the starting position is 1, not 0
The Hashtable class is a subclass of Map and JDK1.0. The Hashtable class is synchronous and thread-safe. It cannot store null keys and null values. Other functions are similar to HashMap.