This question introduces two sort() methods of the Collections tool class, as follows:
1. Two sort() methods of the Collections tool class
Format 1: public static <T extends Comparable<? super T>> void sort(List<T> list)
Note: The generics <T> in this method are all subclasses of the Comparable interface, that is, only data of the Comparable interface subclass type can be compared and sorted. If other types of data are to be compared and sorted, the Comparable interface must be inherited and
Override equals() and compareTo() methods. Among them, String class and Integer class are both Comparable interface subclasses and can be sorted, while basic types cannot be sorted. Comparison items are specified within the class
Format 2: public static <T> void sort(List<T> list, Comparator<? super T> c)
Note: This method specifies the comparison method Comparator<? super T> c, that is, c must implement the Comparator<? super T> interface, override the compareTo() method to specify the comparison item. Comparison items are specified outside the class, which is more flexible
2. Example
Common ways to get strings and numbers in the example:
/** * Generate random and non-repetitive strings: number Generate number of strings*/ public static List<String> generateString(int number) { List<String> listString = new ArrayList<>(); // Used to store the return value List<Integer> length = null; // String length StringBuffer sb = new StringBuffer(); // Intermediate variable int control = 0; // Control number String[] chars = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" }; while (true) { // End of control if ( control==number ) { break; } // Generate a random number and generate 36-bit 2aaab761-4341-4968-aceb-3861ee3824b2 UUID type data String uuid = UUID.randomUUID().toString().replace("-", ""); sb.setLength(0); // Get the length of a random string, the length is not 0 do { length = getDiffNo(1, 11); } while ( length.get(0)==0 ); // Patch together string for (int i=0; i<length.get(0); i++) { String str = uuid.substring(i*3, (i*3+3)); //Convert the str string to hexadecimal and get its value int x = Integer.parseInt(str, 16); //Get the remainder: x % 0x3E--0x3E = 3*16 + 14 = 62, where chars has 62 characters sb.append(chars[x % 0x3E]); } listString.add(sb.toString()); control++; } return listString; } /** * Generate random and non-repetitive numbers: n generate numbers max generate range*/ public static List<Integer> getDiffNo(int n, int max) { // Generate [0-n] non-repetitive random numbers// list Used to save these random numbers List<Integer> list = new ArrayList<>(); Random random = new Random(); Integer k; for (int i=0; i<n; i++) { do { k = random.nextInt(max); } while (list.contains(k)); list.add(k); } return list; } 1. Sort the List of Integer generics
/** * 1. Sort the List of Integer generics through the Collections.sort() method; * Create a List of Integer generics, insert ten non-repetitive random integers within 100, and call the Collections.sort() method to sort them* 2. Sort rules: first number and then letters, numbers 0-9, the order of letters AZ az*/ public void listIntegerSort() { // Insert ten non-repetitive random integers within 100 List<Integer> integerList = getDiffNo(10, 100); System.out.println("----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- integer : integerList) { System.out.println("Element: " + integer); } Collections.sort(integerList); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ 2. Sort the List of String generics
/** * 1. Sort the List of String generics; Create a List of String generics, add out-of-order String elements, * Call the sort method, and output the sort order again*/ public void listStringSort() { List<String> stringList = new ArrayList<String>(); stringList.add("eipJlcx"); stringList.add("WvQRufC"); stringList.add("J"); stringList.add("HdaU2G"); stringList.add("M0WswHD3"); System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- /** * Sort the List of String generics, requiring random generation of 10 non-repetitive strings, and the length of the string is within 10*/ public void listStringRandomSort() { // Generate random string List<String> listString = generateString(10); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- System.out.println("-------------------------------------------------------------"); for (String integer : listString) { System.out.println("Element:" + integer); } }3. Sort List of other types of generics
Course class implementation
/** * Course class* @author Administrator * */public class Course { public String id; public String name; public Course(String id, String name) { this.id = id ; this.name = name; } public Course() { } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Course)) return false; Course other = (Course) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; }} Student class implements Comparable interface and sets comparison items within the class
import java.util.HashSet;import java.util.Set;/** * Student class* @author Administrator * */public class Student implements Comparable<Student> { public String id; public String name; public Set<Course> courses; public Student(String id, String name) { this.id = id; this.name = name; this.courses = new HashSet<Course>(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Student)) return false; Student other = (Student) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } @Override public int compareTo(Student o) { // Set ID as comparison item// TODO Auto-generated method stub return this.id.compareTo(o.id); }} Implement Comparator interface and set comparison items outside the class
import java.util.Comparator;public class StudentComparator implements Comparator<Student> { @Override public int compare(Student o1, Student o2) { // TODO Auto-generated method stub return o1.name.compareTo(o2.name); }} Comparing Student Classes
/** * Sort Lists of other types of generics, taking Student as an example. */ public void listComparatorSort() { List<Student> studentList = new ArrayList<Student>(); List<Integer> list = getDiffNo(4, 1000); studentList.add(new Student(list.get(0) + "", "Mike")); studentList.add(new Student(list.get(1) + "", "Angela")); studentList.add(new Student(list.get(2) + "", "Lucy")); studentList.add(new Student(1000 + "", "Beyonce")); System.out.println("------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ System.out.println("Student:" + student.id + ":" + student.name); } // Implement the Comparator<T> interface, set a specific comparison method, sort by name comparison Collections.sort(studentList, new StudentComparator()); System.out.println("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.