Set interface and Map interface
1. Understanding the characteristics of Set sets 2. Master the Use of Common Implementation Classes under Set Sets 3. Understanding the characteristics of Map collections 4. Master the Use of Common Implementation Classes under Map Set 5. Master the traversal mode of Map set 6. Master Collections Tool Class
Section 1 Set Interface
1.1 Common methods of Set interface
Method Name Description Add (E) Ensure that the collection contains the specified elements (optional operations). AddAll (Collection <? Extends E > c) adds all elements in the specified collection to this collection (optional operation). clear() removes all elements (optional operations) from this collection. contains(Object o) Returns true if the collection contains the specified element. ContainsAll (Collection <?> c) Returns true if the collection contains all elements in the specified collection. equals(Object o) compares whether this collection is equal to the specified object. isEmpty() returns true if the collection does not contain elements. iterator() returns an iterator that iterates over the collection element. remove(Object o) removes a single instance of the specified element from the collection if it exists (optional operation). RemoveAll (Collection <?> c) removes all elements (optional operations) from this collection that are also included in the specified collection. RetainAll (Collection <?> c) retains only those elements in this collection that are also included in the specified collection (optional operations). size() returns the number of elements in this collection. toArray() returns an array containing all elements in this collection.
1.2 Storage Characteristics
Relatively disorderly storage, can not store the same elements (row weight), can not be accessed through Subscripts package com.qf.day16; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * Set interface * Characteristic: disorder, non-repeatability * @author wgy * */
public class Demo1 {
public static void main(String[] args) {
//create object
Set<String> set=new HashSet<String>();
//1Add to
set.add("Chrysanthemum");
set.add("Chinese wolfberry");
set.add("Red dates");
set.add("Ginseng");
set.add("Ganoderma lucidum");
set.add("Chinese wolfberry");
System.out.println("Element number:"+set.size());
System.out.println(set);
//2delete
//2.1Delete one
// set.remove("Ganoderma lucidum");
// System.out.println("After deletion:"+set);
// //2.2empty
// set.clear();
//3ergodic
//3.1foreach
System.out.println("--------Enhance for----------");
for (String string : set) {
System.out.println(string);
}
//3.2Using Iterators
System.out.println("---------iterator-------");
Iterator<String> it=set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//4judge
System.out.println(set.contains("Chrysanthemum"));
System.out.println(set.contains("Plum blossom"));
}
}
1.3 Set Common Implementation Classes
1.3.1 HashSet
This class implements the Set interface, which is supported by a hash table (actually a HashMap instance). It does not guarantee the iteration order of set; in particular, it does not guarantee that the order will remain constant. This class allows null elements to be used. Hash: Hash - The actual meaning of hashing is an algorithm that converts an arbitrary length of input into a fixed length of output through a hashing algorithm. The output is a hash value. Hash table: Array plus linked list has the advantages of both array and linked list. Storage features: Relatively disorderly storage, you can't store the same elements (ranking), through the hash table to achieve the collection
1.3.2 Rewrite hashCode()
hashCode() is a method in Object, and the hashCode value of each object is unique, so it can be understood that the hashCode value represents the location of the object in memory. The hashCode() of string String is calculated on the basis of content. When rearranging HashSet sets, it is necessary to determine whether two objects are the same. The same object can be judged by the hashCode value, so the hashCode() method needs to be rewritten. Case: Design an Animal class, rewrite the hashCode method, and add Animal objects to a HashSet collection. Check weighting (if all attributes are identical, they are considered identical elements)
Code implementation:
public class Animal { private String name; private int age; @Override public String toString() { return "Animal [name=" + name + ", 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; } public Animal() { super(); } public Animal(String name, int age) { super(); this.name = name; this.age = age; } @Override /*Rewrite hashCode() method, simply to check whether this method can achieve the effect of rearrangement, so return a fixed value, so that all objects of this class hashCode value is the same.*/ public int hashCode() { return 1; } } //When multiple Animal objects are added to the HashSet collection, all the attributes are the same, and the desired rearrangement effect is not achieved. //So just rewriting hashCode method can't achieve the desired alignment effect.
1.3.3 Rewrite equals()
The equals() method is a method in the Object class, which means to compare whether two objects are equal or not, if the address of the comparator is not rewritten. So we can try to override the equals method to check weight loss. Case: Design an Animal class, override the equals method, and add Animal objects to a HashSet collection. Check weighting (if all attributes are identical, they are considered identical elements)
Code implementation:
public class Animal { private String name; private int age; @Override public String toString() { return "Animal [name=" + name + ", 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; } public Animal() { super(); } public Animal(String name, int age) { super(); this.name = name; this.age = age; } @Override /*Rewrite hashCode() method, simply to check whether this method can achieve the effect of rearrangement, so return true, so that all objects of this class are equal when compared using equals method.*/ public boolean equals(Object obj) { return true; } } //When multiple Animal objects are added to the HashSet collection, all the attributes are the same, and the desired rearrangement effect is not achieved. //So only rewriting equals method can not achieve the desired alignment effect.
1.3.4 HashSet Set Set Set for Weight Arrangement
Repeated basis for HashSet: hashCode and equals The hashCode and equals methods need to be rewritten simultaneously to achieve weight reduction. Case: Design a Student class and override hashCode and equals methods to check if weight loss is achieved
Code implementation:
public class Student { private String name; public Student(String name) { super(); this.name = name; } public Student() { super(); } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [name=" + name + "]"; } @Override //Rewrite equals public boolean equals(Object obj) { //First, determine whether the incoming parameter object is a Student object, or if it does not return false directly? if(obj instanceof Student) { //If so, strongly convert to Student objects and compare the values of attributes Student s = (Student) obj; if(this.name.equals(s.name)) { //Returns true if the value of the attribute is the same return true; } } return false; } @Override public int hashCode(){ /*hashCode Method return value is int type, so when rewriting, we need to find the data return of int type, and ensure that the return value of this method is related to all the attributes of the object, so the length of the string returning the name attribute*/ return this.name.length(); } }
Rewriting hashCode and equals at the same time can achieve the effect of element rearrangement.
1.3.5 LinkedHashSet
The LinkedHashSet class is a hash table and link list implementation of the Set interface with predictable iteration order (relatively ordered). Is a subclass of HashSet. Storage features: Orderly storage, can not store the same elements (ranking), through the list of collections (doomed to be relatively orderly) The element rearrangement of LinkedHashSet set is consistent with that of HashSet set.
1.3.6 TreeSet collection
A TreeSet collection is an implementation of a Set interface that can reorder elements. The natural order of elements is used to sort the elements, or according to the Comparator provided when the set is created, depending on the construction method used. Storage features: Unordered storage, rearrangement, collection implemented by binary tree, can reorder elements
1.3.7 SortedSet interface
TreeSet implements not only the Set interface, but also the SortedSet interface.
Common methods in the SortedSet interface:
Method Name Description
first() returns the current first (lowest) element in this set.
last() returns the last (highest) element currently in this set.
HeadSet (E to Element) returns a partial view of this set whose elements are strictly smaller than toElement.
TailSet (E from Element) returns a partial view of this set whose elements are greater than or equal to fromElement.
SubSet (E from Element, E to Element) returns a partial view of this set, with elements ranging from fromElement (including) to toElement (excluding).
1.3.8 Element Sorting of TreeSet Sets
Natural ordering
The class to which the element belongs needs to implement the java.lang.Comparable interface and override the compareTo method. In addition to sorting, the compareTo method also has the function of ranking, but all attribute values in the class must be judged in the compareTo method. Otherwise, unless that attribute is compared, the ranking will ignore which attribute.
Case: Designing a Person class to sort all elements when adding Person objects to TreeSet collections
Code implementation:
public class Person implements Comparable<Person> { private String name; private int age; public Person() { super(); } public Person(String name, int age) { super(); this.name = name; this.age = age; } @Override public String toString() { return "Person [name=" + name + ", 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 //Rewrite the compareTo method, sorting by age, descending by name if age is the same public int compareTo(Person o) { //There are two attributes in Person. In this method, we must compare name and age attributes, otherwise we will not be able to weight correctly. if(this.age != o.age) { return this.age - o.age; }else { return o.name.compareTo(this.name); } } }
Custom sort
Elements need to be sized and sorted through the compare method in the java.util.Comparator interface (comparator). In addition to sorting, the comparison method also has the function of ranking, but all attribute values in the class must be judged in the comparison method. Otherwise, unless that attribute is compare d, the ranking method will ignore which attribute. The parameter-free construction method in TreeSet sets defaults to natural sorting for elements. When using custom sorting of TreeSet sets, it is not possible to create collection objects directly using the parameter-free construction method. It is necessary to create collection objects using the construction method passed into a Comparator comparator.
Code implementation:
public class Animal { private String name; private int age; @Override public String toString() { return "Animal [name=" + name + ", 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; } public Animal(String name, int age) { super(); this.name = name; this.age = age; } public Animal() { super(); } } public class AnimalDemo{ public static void main(String[]args){ //Create a TreeSet collection, using anonymous objects of anonymous internal classes of the Comparator interface as comparators TreeSet<Animal> treeSet = new TreeSet<>(new Comparator() { @Override public int compare(Animal o1, Animal o2) { if(o1.age!=o2.age) { return o2.age - o1.age; }else { return o1.name.compareTo(o2.name); } } }); //Additive elements treeSet.add(new Animal("Chinese rhubarb", 1)); treeSet.add(new Animal("Prosperous wealth", 2)); //Ergodic set Iterator<Animal> it = treeSet.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } }
What is the difference between Comparable and Comparator?
1 Collection elements need to implement Comparable interface, called natural sorting, Comparator is a comparator to achieve customized sorting.
2 Comparable compareTo() a parameter, Comparator compare() two parameters, return value is int type.
If it returns 0, it means that the two comparison elements are the same, if it is greater than 0, the front is larger than the back, and if it is less than 0, the front is smaller than the back.
Computer Practice: Arrange strings according to the length of letters, if the length is the same, in the order of coding.
"dog" "hello" "beijing" "tianjin" "shanghai" "guangzhou"
package com.qf.day16_2; import java.util.Comparator; import java.util.TreeSet; /** * Computer Practice: Arrange strings according to the length of letters, if the length is the same, in the order of coding. * @author wgy *"dog" "hello" "beijing" "tianjin" "shanghai" "guangzhou" */ public class Demo1 { public static void main(String[] args) { TreeSet<String> treeSet=new TreeSet<String>(new Comparator<String>() { @Override public int compare(String o1, String o2) { int n=o1.length()-o2.length(); int m=o1.compareTo(o2); return n!=0?n:m; } }); treeSet.add("beijing"); treeSet.add("guangzhou"); treeSet.add("shanghai"); treeSet.add("tianjin"); treeSet.add("hello"); treeSet.add("dog"); treeSet.add("no"); System.out.println(treeSet); } }
Section 2 Map Interface
2.1 overview
The Map interface is an object that maps keys to values. A mapping cannot contain duplicate keys; each key can be mapped to at most one value. Cn---> China USA - > USA Uk---> UK Us---> us
2.2 Common methods of Map interface
Method Name Description clear() removes all mapping relationships (optional operations) from this map. containsKey(Object key) returns true if the mapping contains the mapping relationship for the specified key. containsValue(Object value) returns true if the mapping maps one or more keys to a specified value. entrySet() returns the Set view of the mapping relationship contained in this mapping. equals(Object o) compares whether the specified object is equal to this mapping. get(Object key) returns the value mapped by the specified key; if the mapping does not contain the mapping relationship of the key, it returns null. hashCode() returns the hash code value of this mapping. isEmpty() returns true if the mapping does not contain a key-value mapping relationship. keySet() returns the Set view of the key contained in this map. put(K key, V value) associates the specified value with the specified key in this mapping (optional operation). PuputAll (Map <? Extends K,? Extends V > m) copies all mapping relationships from the specified mapping to this mapping (optional operation). remove(Object key) If there is a key mapping relationship, remove it from the mapping (optional operation). size() returns the number of key-value mapping relationships in this map.
2.3 Map Common Implementation Classes
2.3.1 HashMap
Implementation of Map interface based on hash table. This implementation provides all optional mapping operations and allows null values and null keys to be used. This class does not guarantee the order of mappings. Storage features: Relatively disorderly storage, elements exist in the form of key-value pairs, keys can not be repeated, values can be repeated, the overall weight of elements, can quickly find the corresponding values through key lookup, through the hash table set. The weighting of a Map set requires only rewriting the hashCode and equals methods of the class to which the key belongs.
Code implementation:
//Person as the key
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
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 "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode() {
return age + name.length();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Person) {
Person p = (Person) obj;
if(p.name.equals(name)&&p.age==age) {
return true;
}
}
return false;
}
}
//Dog class as value
public class Dog {
private String name;
public Dog(String name) {
super();
this.name = name;
}
public Dog() {
super();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog [name=" + name + "]";
}
}
//Test class
public class Demo {
public static void main(String[] args) {
HashMap<Person, Dog> map = new HashMap<>();
map.put(new Person("zhangsan", 12), new Dog("Chinese rhubarb"));
map.put(new Person("lisi", 12), new Dog("Prosperous wealth"));
map.put(new Person("zhangsan", 12), new Dog("Two ha"));
}
}
If the same key-value pair is added to the map set, the new value will override the old value. In the above code, there are two key-value pairs in the map set: Zhang San-12-Erha, lisi-12-Wangcai.
2.3.2 LinkedHashMap
LinkedHashMap collection is a hash table and link list implementation of Set interface with predictable iteration order. This implementation differs from HashSet in that it maintains a list of double links running on all entries. The usage is similar to HashSet. Storage features: Orderly storage, element rearrangement, set through linked list.
2.3.3 Hashtable
This class implements a hash table that maps keys to corresponding values. Any non-null object can be used as a key or value. Storage features: Relatively disorderly storage, element rearrangement, set implemented by hash table.
2.3.4 Differences between HashMap and Hashtable
1) Hashtable threads are safe, while HashMap threads are not. 2) Null keys and null values are not allowed in Hashtable, but null keys and null values are allowed in HashMap.
2.4 Traversal of Map Sets
2.4.1 Combine keySet method with get method
public class Demo { public static void main(String[] args){ HashMap<String, Integer> map = new HashMap<>(); map.put("aaa", 12); map.put("bbb", 13); map.put("ccc", 14); //Get all keys in map through keySet Set<String> set = map.keySet(); //Iterator for Getting set Iterator<String> it = set.iterator(); while(it.hasNext()){ String s = it.next(); //Iterative keys are used to find the corresponding values and output them together. System.out.println(s+"---"+map.get(s)); } } }
2.4.2 Using Map.Entry method:
Calling the entrySet method of the Map set is equivalent to turning the Map set into a Set set, and then traversing through the Set set.
Code implementation:
public class Demo { public static void main(String[] args) { HashMap<String, Integer> map = new HashMap<>(); map.put("aaa", 111); map.put("bbb", 222); map.put("ccc", 333); //Convert map into a Set set Set Set<Map.Entry<String, Integer>> set = map.entrySet(); //Traversing set Iterator<Map.Entry<String, Integer>> it = set.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }
Summary:
The common method in Collection parent interface collection is add () remove () contains () size ():
Characteristic: Some things are orderly, some things are disorderly, some can be repeated, some can not be repeated
List: Features: orderly, repeatable ArrayList: Storage structure arrays are suitable for traversal lookups LinkedList: Storage structure linked list suitable for insertion and deletion Vector vector Stack: First in, last out Set: Characteristic: disorder, no repetition HashSet: Storage structure: Hash table is out of order and cannot be repeated: repeat basis: hashCode () equals () LinkedHashSet: Storage Structure: Hash Table Order TreeSet: Storage structure: red-black self-balanced binary tree is disordered, sorted, and can not be repeated: Repetitive basis: Comparable interface compareTo(); return value 0 is repetitive. Comparator: Comparator, compare (o1, o2) {} if the return value is 0 duplicate elements
Map features: store key-value pairs, keys can not be repeated, a key corresponds to a value, the value can be repeated
HashMap: Storage structure: hash table, disorder, keys can not be repeated: repeat basis: hashCode () equals () LinkeHashMap: Storage Structure: Hash Table, Order Hashtable: The set of jdk1.0 can't store null keys and null values. Thread-safe. - Properties: No TreeMap: Storage Structure: Red-Black Self-Balanced Binary Tree
Hash-based storage structure hash tables hashCode and equals
Comparable Comparator for Storage Binary Tree Sorting at the Beginning of Tree
Link starts out orderly
Section 3 Collections Tool Class
This class consists entirely of static methods that operate on Collection or return Collection. Static methods in this class can be used when manipulating collections.
3.1 Common methods in Collections
1. Synchronization threads
/* static <T> Collection<T> synchronizedCollection(Collection<T> c) Returns a synchronous (thread-safe) collection supported by the specified collection. static <T> List<T> synchronizedList(List<T> list) Returns a synchronized (thread-safe) list supported by the specified list. static <K,V> Map<K,V> synchronizedMap(Map<K,V> m) Returns a synchronous (thread-safe) mapping supported by the specified mapping. static <T> Set<T> synchronizedSet(Set<T> s) Returns the synchronous (thread-safe) set supported by the specified set. */ Collection c = Collections.synchronizedCollection(new ArrayList()); List s = Collections.synchronizedList(new ArrayList()); Map m = Collections.synchronizedMap(new HashMap());
2. ranking
/* static <T extends Comparable<? super T>> void sort(List<T> list) Sort the specified list in ascending order according to the natural order of elements. */ ArrayList<Integer> list = new ArrayList<>(); list.add(-10); list.add(5); list.add(3); list.add(7); System.out.println(list); Collections.sort(list);//Default ascending order System.out.println(list);
3. Inversion of elements in a collection
/* static void reverse(List<?> list) Reverses the order of elements in the specified list. */ Collections.reverse();
4. Disturbing Collection Elements
/* static void shuffle(List<?> list) Use the default random source to permute the specified list. */
5. Get the maximum and minimum values in the set
/* static T max(Collection coll) Returns the largest element of a given collection according to its natural order. static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) Returns the minimum element of a given collection in its natural order. */ int n1 = Collections.max(list);
6. replacement
/* static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) Replace all specified values in the list with another value */ //Reason: List collections are unrestricted, using new elements to replace all the old elements that appear in the collection Collections.replaceAll(list,5,100);
7. Statistics of the number of occurrences of specified elements in a collection
/* static int frequency(Collection<?> c, Object o) Returns the number of elements equal to the specified object in the specified collection. */ int num = Collections.frequency(list,5);
8. Dichotomy Search
/* static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key) Binary search is used to search the specified list for the specified object. */ //Prerequisite: must be an ordered set int index = Collections.binarySearch(list,-10); //Note: The methods in the Collections tool class only operate on the Collection interface, and the List interface is the main operation.
9. Conversion of sets and arrays
1 Converting arrays to collections package com.qf.day16; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Demo2 { public static void main(String[] args) { //arrayToList(); //listToArray(); arrayToList2(); } //1. Arrays are turned into collections. Collections cannot be added or deleted. public static void arrayToList() { String[] names= {"Zhang San","Li Si","Wang Wu"}; List<String> list=Arrays.asList(names); System.out.println("list: "+list); //Add to //list.add("Zhao Liu"); //delete //list.remove(0); //System.out.println("list:"+list after adding or deleting); list.set(0, "Ben Wei"); System.out.println("After replacement:"+list); } //2 sets into arrays public static void listToArray() { ArrayList<String> arrayList=new ArrayList<>(); arrayList.add("Apple"); arrayList.add("millet"); arrayList.add("HUAWEI"); arrayList.add("Samsung"); //array String[] arr=arrayList.toArray(new String[0]); System.out.println("--------foreach-------"); for (String string : arr) { System.out.println(string); } } //3 special public static void arrayToList2() { Integer[] nums= {10,20,5,8,9}; List<Integer> arraylist=Arrays.asList(nums); for (Integer integer : arraylist) { System.out.println(integer); } } }
summary
Collection |_____List (Characteristic: Orderly, repeatable) |___ArrayList (storage structure:Array) |___LinkedList (Linked list) |___Vector array |___Stack Array (stack) FIFO | |_____Set(Characteristic:Unordered, not repeatable) |_____HashSet Hashtable(Array plus linked list) 1 implement hashCode()To calculate the location of storage, 2 executes equals Comparison results |____LinkedHashSet Hash tables guarantee order |_____TreeSet Realization of Self-Balanced Red-Black Binary Tree Element 1 Comparable Interface, 2 Custom Comparator Comparator Map(Features: Store key-value pairs, keys can not be repeated, values can be repeated, disorderly) |______ HashMap Hash Table 1 Execution hashCode()To calculate the location of storage, 2 executes equals Comparison results |______ Hashtable Hash table cannot be stored null Key sum null Value, thread-safe jdk1.0 |_______LinkedHashMap Hash tables guarantee order |_______TreeMap Self-balanced red-black binary tree 1 key To achieve Comparable Interface, 2 Custom Comparator Comparator Collections Use of tool classes.