TreeSet collection
TreeSet collection features
-
Elements are ordered, not stored and retrieved, but sorted according to certain rules, depending on the constructor
- TreeSet(): Sorts according to the natural ordering of its elements
- TreeSet(Comparator Comparator) : Sorts according to the specified Comparator
-
There are no indexed methods, so you can’t iterate with a normal for loop
-
A Set that contains no repeating elements because it is a Set
Use of natural sort Comparable
● Store student objects and iterate over them to create a TreeSet collection using the no-parameter constructor requires: Sort by age from youngest to oldest, alphabetically by name for the same age
-
public interface Comparable<T> Copy the code
This interface imposes a global sort on the objects of each class that implements it. This sort is called the natural sort of a class, and the compareTo method of a class is called its natural comparison method.
Collections.sort (and arrays.sort) automatically sort lists (and Arrays) of objects that implement this interface. An object that implements this interface can be used as a sorted map on a key or as a sorted set on a component without specifying a comparator.
The natural order of class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 for every E1 and the same Boolean value e1.equals(e2) for class C e2. Note that null is not an instance of any class, and e.compareTo(NULL) should throw a NullPointerException even if E.quals (null) returns false.
Example:
public class Student implements Comparable<Student>{
private String name;
private int age;
public Student(a) {}public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName(a) {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge(a) {
return age;
}
public void setAge(int age) {
this.age = age;
}
// Override the interface Comparable method so that the collection can be sorted by age
@Override
public int compareTo(Student o) {
// Sort from youngest to oldest
int num = this.age - o.age;
// Sort in alphabetical order at the same age
int num2 = num==0?this.name.compareTo(o.name):num;
returnnum2; }}Copy the code
public class SetDemo {
public static void main(String[] args) {
TreeSet<Student> st = new TreeSet<Student>();
Student s1 = new Student("zhangsan".32);
Student s2 = new Student("lisi".31);
Student s3 = new Student("hejin".37);
Student s4 = new Student("daoming".35);
Student s5 = new Student("xiaohan".27);
Student s6 = new Student("feizi".31);
st.add(s1);
st.add(s2);
st.add(s3);
st.add(s4);
st.add(s5);
st.add(s6);
for(Student i:st){
System.out.println(i.getName() + ":"+ i.getAge()); }}}Copy the code
Effect:
conclusion
- The TreeSet collection is used to store custom objects. The no-argument constructor uses natural sorting to sort elements
- The natural sort is to have the class to which the element belongs implement the Comparable interface, overriding the compareTo(T o) method
- When overriding a method, be sure to note that collation rules must be written according to the required primary and secondary conditions
Realize random number that does not repeat
public class ListDemo {
public static void main(String[] args) {
// Set
s = new HashSet
();
// It will sort naturally
Set<Integer> s = new TreeSet<Integer>();
// Random number object
Random r = new Random();
// The number of collections is not greater than 10
while (s.size()<10) {int num = r.nextInt(21);
s.add(num);
}
for (inti:s) { System.out.println(i); }}}Copy the code
The generic
Generic overview
Generics: a feature introduced in JDK5 that provides compile-time type-safety checks that allow illegal types to be detected at compile time
Its essence is parameterized typing, which means that the data type being operated on is specified as a parameter
When it comes to parameters, you’re most familiar with defining tangible arguments to a method and then passing the arguments when the method is called. So what about parameterized types?
As the name implies, you parameterize the type from the original concrete type, and then pass in the concrete type when you use/call it
This parameter type can be used in classes, methods, and interfaces, known as generic classes, generic methods, and generic interfaces, respectively
Generic definition format:
- < type >: Specifies the format of a type. The types here can be thought of as parameters
- < Type 1, type 2… > : Specifies the format of multiple types, separated by commas. The types here can be thought of as parameters
- A given type can be treated as an argument in a future call, and the type of the argument can only be a reference data type
Example:
Collection c = new ArrayList();
// Use generics to resolve promiscuous sets of int and string
Collection<String> c = new ArrayList<String>();
Copy the code
Benefits of generics:
- Bring run-time problems forward to compile time
- Casting is avoided
A generic class
Example:
public class Generic<T> {
private T t;
public T getT(a) {
return t;
}
public void setT(T t) {
this.t = t; }}Copy the code
public class ListDemo {
public static void main(String[] args) {
Generic<String> s = new Generic<>();
s.setT("Water margin");
System.out.println(s.getT());
Generic<Integer> n = new Generic<>();
n.setT(100); System.out.println(s.getT()); }}Copy the code
Results:
Generic method
public class Generic {
public <T> void show(T t){ System.out.println(t); }}Copy the code
public class ListDemo {
public static void main(String[] args) {
Generic g = new Generic();
g.show("Li Mu");
g.show(100);
g.show(true);
g.show(12.56); }}Copy the code
Results:
Type wildcard
To represent the parent classes of various generic lists, you can use type wildcards
- Type wildcard:
- List
: represents a List of unknown elements whose elements can match any type - This wildcard List simply means that it is a parent of the various generic lists, and you cannot add elements to them
If we don’t want List<? > is the parent of any generic List. You only want it to represent the parent of a certain class of generic List. You can use the upper bound of type wildcards
- Type wildcard upper limit:
- List
: This represents the type Number or its subtype
In addition to specifying the upper limit of type wildcards, we can also specify the lower limit of type wildcards
- Type wildcard lower limit:
- List
: It represents either Number or its parent type
Example:
public class ListDemo {
public static void main(String[] args) {
// Type wildcard:
List<? > list1 =newArrayList<Object>(); List<? > list2 =newArrayList<Number>(); List<? > list3 =new ArrayList<Integer>();
// Type wildcard upper limit:
List<? extends Number> list4 = new ArrayList<Integer>();
// Type wildcard lower limit:
List<? super Number> list5 = newArrayList<Object>(); }}Copy the code
Variable parameter
A variable parameter, also known as a variable number of parameters, is used as a parameter of a method, so the number of parameters of the method is variable
- Format: modifiers return value type method name (data type.. Variable name {}
- Public static int sum(int… a){ }
Example:
public class ListDemo {
public static void main(String[] args) {
System.out.println(Sum(10.20));
System.out.println(Sum(10.20.30));
System.out.println(Sum(10.20.30.40.50));
}
public static int Sum(int. a){
// Turn the data into an array, output a is the array address
System.out.println(a);
int sum=0;
for(int i:a){
sum+=i;
}
returnsum; }}Copy the code
Results:
Map
-
public interface Map<K,V> Copy the code
An object that maps keys to values. Maps cannot contain duplicate keys; Each key can map to at most one value.
This interface replaces the Dictionary class, which is a completely abstract class rather than an interface.
The Map interface provides three collection views that allow you to view the contents of a Map as a set of keys, a set of values, or a set of key-value maps. The order of the map is defined as the order in which the collection view iterates over the map to return elements. Some map implementations, such as the TreeMap course, make specific guarantees on their orders; Others, like the HashMap class, don’t.
Note: Be very careful when using mutable objects as map keys. If the value of an object changes in a way that affects the equals comparison, and the object is a key in the map, the behavior of the map is not specified. A special case of this prohibition is that maps are not allowed to include themselves. Although a map can be used as a value in itself, you are advised to be very careful: the equals and hashCode methods are less explicit on such a map.
All generic mapping implementation classes should provide two “standard” constructors: a void (no arguments) constructor that creates an empty Map, and a constructor with a single argument of type Map that creates a new Map Map with the same key value as the argument. In fact, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (because the interface cannot contain constructors), and all generic mapping implementations in the JDK fit the bill.
Creates an object for the Map collection
- Polymorphic way
- The concrete implementation class HashMap
Example :(note that keys are unique in a map)
import java.util.HashMap;
import java.util.Map;
public class MapDemo {
public static void main(String[] args) {
// Create a map collection object
Map<String,String> map = new HashMap<String,String>();
// Add objects using the put method
map.put("map1"."Heaven and earth");
map.put("map2"."Xuan huang");
map.put("map3"."The universe");
map.put("map4"."The big"); System.out.println(map); }}Copy the code
Results:
Traversal of Map collection:
-
Gets a collection of all key-value pair objects
- Set< map.entry
,v>
> entrySet(): Gets a collection of all key-value pair objects
- Set< map.entry
-
Iterating through the collection of key-value objects, obtaining each key-value object
- Implemented with enhanced for, get each map.entry
-
Gets keys and values from key-value pairs
- Get the key with getKey()
- Use getValue() to get the value
Example:
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
// Create a map collection object
Map<String,String> map = new HashMap<String,String>();
// Add objects using the put method
map.put("map1"."Heaven and earth");
map.put("map2"."Xuan huang");
map.put("map3"."The universe");
map.put("map4"."The big");
// Get the object of the set of all key values
Set<Map.Entry<String,String>> entrySet = map.entrySet();
// Iterate over the set of key and value objects to get each object
for(Map.Entry<String,String> i:entrySet){
// Get the key and value from the key value object
String key = i.getKey();
String value = i.getValue();
System.out.println(key+":"+value); }}}Copy the code
Results:
A HashMap nested ArrayList
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
// Create a HashMap collection
HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
// Create an Arraylist collection and add elements
ArrayList<String> sgyy = new ArrayList<String>();
sgyy . add( "Zhuge Liang");
sgyy. add("Zhaoyun");
// Add ArrayL IST as an element to the HashMap collection
hm. put(Romance of The Three Kingdoms ,sgyy);
ArrayList<String> xyj = new ArrayList<String>();
xyj. add("Tang's monk");
xyj. add("Sun Wukong");
// Add ArrayL IST as an element to the HashMap collection
hm. put(Journey to the West,xyj);
ArrayList<String> shz = new ArrayList<String>();
shz . add("Wu song");
shz.add("Lu Zhishen");
// Add ArrayL IST as an element to the HashMap collection
hm. put("Water Margin",shz);
// Iterate over the HashMap collection
Set<String> keySet = hm. keySet();
for(String key : keySet) {
System.out.println(key);
ArrayList<String> value = hm.get(key);
for (String s : value) {
System.out.println("\t"+ s); }}}}Copy the code
Results:
Example: Count the number of occurrences of each character in a string
Requirement: keyboard input a string, the number of occurrences of each string in the string. Example: Keyboard input “aababcabcdabcde” on the console output: “A (5) B (4) C (3) D (2)e(1)”
-
① Keyboard input a string
-
Create a HashMap with Character as key and Integer as value
-
③ Iterate over the string to get each character
-
④ Take each character as a key into the HashMap collection to find the corresponding value and see its return value
- If the return value is null: the character does not exist in the HashMap collection and is stored as a key and 1 as a value
- If the return value is not null: the character exists in the HashMap collection, increment the value by one, and then re-store the character and its corresponding value
-
⑤ Iterate through the HashMap collection to get keys and values, and splice them as required
-
⑥ Output result
Code:
public class MapDemo {
public static void main(String[] args) {
// The keyboard enters a string
Scanner sc = new Scanner(System. in);
System.out.println("Please enter a string:");
String line = sc.nextLine();
// Create a HashMap collection with the key Character and value Integer
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
// Iterate over the string to get each character
for (int i = 0; i < line.length(); i++) {
char key = line.charAt(i);
// Take each character as a key into the HashMap collection to find the corresponding value and see its return value
Integer value = hm.get(key);
if (value == null) {
// If the return value is null: the character does not exist in the HashMap collection, the character is stored as the key and 1 as the value
hm.put(key, 1);
} else {
// If the return value is not null, the character exists in the HashMap collection, increment the value by one, and then store the character and its corresponding value againvalue++; hm.put(key, value); }}// Iterate over the HashMap collection, get the keys and values, and concatenate as required
StringBuilder sb = new StringBuilder();
Set<Character> keySet = hm.keySet();
for(Character key : keySet) {
Integer value = hm. get(key);
sb.append(key).append("(").append(value).append(")"); } System.out.println(sb); }}Copy the code
Results:
Collections
-
public class Collections extends Object Copy the code
This class is composed or returned by static methods only. It contains polymorphic algorithms that operate on sets, “wrappers”, returns new sets supported by specified sets, and a few other possible and final ones.
Methods of this class all throw a NullPointerException if the collection or class object provided to them is NULL.
Documentation for polymorphic algorithms included in this class usually includes a brief description of the implementation. These descriptions should be considered as an implementation note, not part of a specification. Implementers are free to substitute other algorithms as long as the specification itself is followed. (For example, the algorithm sort uses doesn’t have to be a Mergeesort, but it does have to be stable.)
An overview of the Collections class
- Is a work class for collection operations
Common methods of the Collections class
- public static
> void sort(List
List): sort the specified List in ascending order
- public static void reverse(List
list): reverses the order of the elements in the specified list - public static void shuffle(List
list): Randomly arranges the specified list using the default random source
Example:
public class MapDemo {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
// Add elements
list.add(30);
list.add(20);
list.add(50);
list.add(10);
list.add(40);
//public static
> void sort (List
List): sort the specified List in ascending order
Collections.sort(list);
//public static void reverse (List
list): reverses the order of the elements in the specified list
Collections.reverse(list);
//public static void shuffle (List
list): Randomly arranges the specified list using the default random source
//Collections.shuffle(list);System.out.println(list); }}Copy the code
Results:
Learn together and make progress together. If there are any mistakes, please comment