“This is the fifth day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
1.Collections common functions
-
Java.utils.collections is a collection utility class that operates on Collections.
The common methods are as follows:
-
public static void shuffle(List
list): shuffles the collection order. -
Public static
void sort(List
List): sort the elements of the collection by default.
-
Public static
void sort(List
List, Comparator
): sorts the elements in the collection according to the specified rule.
Code demo:
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(100);
list.add(300);
list.add(200);
list.add(50);
// Sort methodsCollections.sort(list); System.out.println(list); }}Copy the code
Results:
[50.100.200.300]
Copy the code
Our collections are arranged in the default natural order. What if we want to specify the order?
2. com parator comparator
So let’s do that first
Public static
void sort(List
List): sort the elements of the collection by default.
But this time it’s a string.
public class CollectionsDemo2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("cba");
list.add("aba");
list.add("sba");
list.add("nba");
// Sort methodsCollections.sort(list); System.out.println(list); }}Copy the code
Results:
[aba, cba, nba, sba]
Copy the code
We are using the default rules for sorting strings, so how do we define the default rules?
JAVA provides two ways to compare the size of two objects. One is implemented using the java.lang.Comparable. One is the flexibility to do the sorting when I need to do it in the java.util.Comparator interface to select.
Public static
void sort(List
List) public static
void sort(List
List)
public final class String implements java.io.Serializable.Comparable<String>, CharSequence {
Copy the code
The String class implements this interface and defines the comparison rules, but it kills the rules, so if I want the String to be sorted in descending order by the first character, then I have to change the String source code, which is not possible, then we can use it
Public static
void sort(List
List, Comparator
) method uses the java.util package. Sorting is one of the Comparator’s features. As the name implies is to do sorting, colloquially speaking, the need to compare two objects who ranked first and who ranked last, then the method of comparison is:
-
Public int compare(String o1, String o2) : compares the order of its two arguments.
Two objects can be compared in three ways: greater than, equal to, or less than.
If you want to sort in ascending order o1 is less than O2, return (negative), equal 0 if 01 is greater than 02 if you want to sort in descending order o1 is less than O2, return (positive), equal 0 if 01 is greater than 02 (negative)
The operation is as follows:
public class CollectionsDemo3 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("cba");
list.add("aba");
list.add("sba");
list.add("nba");
// Sort by descending order of the first word
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.charAt(0) - o1.charAt(0); }}); System.out.println(list); }}Copy the code
The results are as follows:
[sba, nba, cba, aba]
Copy the code
3. Describe the differences between Comparable and Comparator
Comparable: Force an overall ordering of objects for 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. You can only implement compareTo() once in a class, and you can’t change the code of the class as often as you want. Lists (and Arrays) of objects implementing this interface can be sorted automatically through collections.sort (and arrays.sort), and objects can be used as keys in ordered maps or elements in ordered Collections without specifying a comparator.
Comparator: Forces a global sort of an object. You can pass a Comparator to a sort method such as collections.sort or arrays.sort, allowing for precise control over sort order. You can also use comparators to control the order of certain data structures, such as ordered sets or ordered maps, or to provide sorting for collections of objects that have no natural order.
4. Variable parameters
After JDK1.5, if we define a method that takes multiple arguments of the same type, we can simplify it.
Format:
Modifier returns value type method name (parameter type... Parameter name){}Copy the code
Code demo:
public class ChangeArgs {
public static void main(String[] args) {
int sum = getSum(6.7.2.12.2121);
System.out.println(sum);
}
public static int getSum(int. arr) {
int sum = 0;
for (int a : arr) {
sum += a;
}
returnsum; }}Copy the code
Note:
1. A method can have only one variable argument
2. If the method has more than one parameter, the variable parameter should be put last.
Application scenario: Collections
Methods for adding elements are also provided in Collections:
public static
boolean addAll(Collection
c, T… Elements: Adds some elements to the collection.
Code demo:
public class CollectionsDemo {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
//
//list.add(12);
//list.add(14);
//list.add(15);
//list.add(1000);
// Add elements to the collection using the utility class
Collections.addAll(list, 5.222.1.2);
System.out.println(list);
}
Copy the code
Practice 5.
Create a student class and store it in the ArrayList collection to perform the specified sorting operation.
Initial class Student
public class 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
public String toString(a) {
return "Student{" +
"name='" + name + ' '' + ", age=" + age + '}'; }}Copy the code
The test class:
public class Demo {
public static void main(String[] args) {
// Create four student objects to store in the collection
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("rose".18));
list.add(new Student("jack".16));
list.add(new Student("abc".16));
list.add(new Student("ace".17));
list.add(new Student("mark".16));
/* In ascending order by age */
// Collections.sort(list); The list must implement the comparator Comparable interface
for(Student student : list) { System.out.println(student); }}}Copy the code
We found an error when we called the collections.sort () method.
Reason: If you want elements in a collection to be sorted, you must implement the comparator Comparable interface.
So we have completed an implementation of the Student class as follows:
public class Student implements Comparable<Student>{...@Override
public int compareTo(Student o) {
return this.age-o.age;/ / ascending}}Copy the code
Once again, the code is OK and looks like this:
Student{name='jack', age=16}
Student{name='abc', age=16}
Student{name='mark', age=16}
Student{name='ace', age=17}
Student{name='rose', age=18}
Copy the code
6. Extension
If you want to define the collections. sort(List List,Comparetor
c), you can define your own rules:
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o2.getAge()-o1.getAge();// In descending order by student's age}});Copy the code
Effect:
Student{name='rose', age=18}
Student{name='ace', age=17}
Student{name='jack', age=16}
Student{name='abc', age=16}
Student{name='mark', age=16}
Copy the code
For more rules, see the following code:
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// Age in descending order
int result = o2.getAge()-o1.getAge();// Age in descending order
if(result==0) {// The first rule determines the ascending first letter of the next rule's name
result = o1.getName().charAt(0)-o2.getName().charAt(0);
}
returnresult; }});Copy the code
The effect is as follows:
Student{name='rose', age=18}
Student{name='ace', age=17}
Student{name='abc', age=16}
Student{name='jack', age=16}
Student{name='mark', age=16}
Copy the code