JAVA Collections tool class
Main analysis content:
1. Two sort() methods of Collections tool class
2. Examples
1. Two sort() methods of Collections tool class
Format 1: public static
Explanation: The generics
Format 2: public static
void sort(List list, Comparator
interface, override Write the compareTo() method to specify the comparison items. The comparison items are specified outside the class, which is more flexible super T> super T>
2. Example
Common methods for obtaining strings and numbers in the example:
/** * 生成随机 不重复的字符串 : number 生成字符串个数 */ public static List<String> generateString(int number) { List<String> listString = new ArrayList<>(); // 用于存放返回值 List<Integer> length = null; // 字符串长度 StringBuffer sb = new StringBuffer(); // 中间变量 int control = 0; // 控制个数 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) { // 控制结束 if ( control==number ) { break; } // 生成随机数,生成36位的2aaab761-4341-4968-aceb-3861ee3824b2 UUID类型数据 String uuid = UUID.randomUUID().toString().replace("-", ""); sb.setLength(0); // 获得随机字符串长度,长度不为0 do { length = getDiffNo(1, 11); } while ( length.get(0)==0 ); // 拼凑字符串 for (int i=0; i<length.get(0); i++) { String str = uuid.substring(i*3, (i*3+3)); //将str字符串转换为16进制,获得其值 int x = Integer.parseInt(str, 16); //取余:x % 0x3E--0x3E = 3*16 + 14 = 62, 其中chars有62个字符 sb.append(chars[x % 0x3E]); } listString.add(sb.toString()); control++; } return listString; } /** * 生成随机不重复的数字 :n生成个数 max生成范围 */ public static List<Integer> getDiffNo(int n, int max) { // 生成 [0-n] 个不重复的随机数 // list 用来保存这些随机数 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 Integer generic List
/** * 1.通过Collections.sort()方法,对Integer泛型的List进行排序; * 创建一个Integer泛型的List,插入十个100以内的不重复随机整数, 调用Collections.sort()方法对其进行排序 * 2.排序规则:先数字后字母,数字0-9,字母A-Z a-z的顺序 */ public void listIntegerSort() { // 插入十个100以内的不重复随机整数 List<Integer> integerList = getDiffNo(10, 100); System.out.println("-------------排序前--------------"); for (Integer integer : integerList) { System.out.println("元素:" + integer); } Collections.sort(integerList); System.out.println("----------------排序后-------------------"); for (Integer integer : integerList) { System.out.println("元素:" + integer); } }
2. Sort the String generic Sort the List of other types
/** * 1.对String泛型的List进行排序; 创建String泛型的List,添加乱序的String元素, * 调用sort方法,再次输出排序后的顺序 */ 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("------------排序前-------------"); for (String string : stringList) { System.out.println("元素:" + string); } Collections.sort(stringList); System.out.println("--------------排序后---------------"); for (String string : stringList) { System.out.println("元素:" + string); } }
/** * 对String泛型的List进行排序,要求随机生成10个的不重复字符串,字符串的长度在10以内 */ public void listStringRandomSort() { // 生成随机字符串 List<String> listString = generateString(10); System.out.println("--------------排序前---------------"); for (String integer : listString) { System.out.println("元素:" + integer); } // 排序 Collections.sort(listString); System.out.println("----------------排序后------------------"); for (String integer : listString) { System.out.println("元素:" + integer); } }
3. Sort the List of other types of generics
Course class implementation
/** * 课程类 * @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 the Comparable interface, set the comparison item within the class
import java.util.HashSet; import java.util.Set; /** * 学生类 * @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) { // 设置ID为比较项 // TODO Auto-generated method stub return this.id.compareTo(o.id); } }
implement the Comparator interface, and set the comparison item 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); } }
Compare Student class
/** * 对其他类型泛型的List进行排序,以Student为例。 */ 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("--------------排序前---------------"); for (Student student : studentList) { System.out.println("学生:" + student.id + ":" + student.name); } // 实现Comparator<T>接口,设置ID比较方式 Collections.sort(studentList); System.out.println("----------------按照ID排序后------------------"); for (Student student : studentList) { System.out.println("学生:" + student.id + ":" + student.name); } // 实现Comparator<T>接口,设置特定比较方式,以name比较排序 Collections.sort(studentList, new StudentComparator()); System.out.println("----------------按照姓名排序后-----------------"); for (Student student : studentList) { System.out.println("学生:" + student.id + ":" + student.name); } }
Reference learning connection:
Implementation and use of Comparable interface: http://www.cnblogs.com/gnuhpc/archive/2012/12/17/2822251.html
Collections.sort Two ways to sort List: http://blog.csdn.net/wxx614817/article/details/50628197

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using the chrono library in C can allow you to control time and time intervals more accurately. Let's explore the charm of this library. C's chrono library is part of the standard library, which provides a modern way to deal with time and time intervals. For programmers who have suffered from time.h and ctime, chrono is undoubtedly a boon. It not only improves the readability and maintainability of the code, but also provides higher accuracy and flexibility. Let's start with the basics. The chrono library mainly includes the following key components: std::chrono::system_clock: represents the system clock, used to obtain the current time. std::chron

Measuring thread performance in C can use the timing tools, performance analysis tools, and custom timers in the standard library. 1. Use the library to measure execution time. 2. Use gprof for performance analysis. The steps include adding the -pg option during compilation, running the program to generate a gmon.out file, and generating a performance report. 3. Use Valgrind's Callgrind module to perform more detailed analysis. The steps include running the program to generate the callgrind.out file and viewing the results using kcachegrind. 4. Custom timers can flexibly measure the execution time of a specific code segment. These methods help to fully understand thread performance and optimize code.

C code optimization can be achieved through the following strategies: 1. Manually manage memory for optimization use; 2. Write code that complies with compiler optimization rules; 3. Select appropriate algorithms and data structures; 4. Use inline functions to reduce call overhead; 5. Apply template metaprogramming to optimize at compile time; 6. Avoid unnecessary copying, use moving semantics and reference parameters; 7. Use const correctly to help compiler optimization; 8. Select appropriate data structures, such as std::vector.

DMA in C refers to DirectMemoryAccess, a direct memory access technology, allowing hardware devices to directly transmit data to memory without CPU intervention. 1) DMA operation is highly dependent on hardware devices and drivers, and the implementation method varies from system to system. 2) Direct access to memory may bring security risks, and the correctness and security of the code must be ensured. 3) DMA can improve performance, but improper use may lead to degradation of system performance. Through practice and learning, we can master the skills of using DMA and maximize its effectiveness in scenarios such as high-speed data transmission and real-time signal processing.

C performs well in real-time operating system (RTOS) programming, providing efficient execution efficiency and precise time management. 1) C Meet the needs of RTOS through direct operation of hardware resources and efficient memory management. 2) Using object-oriented features, C can design a flexible task scheduling system. 3) C supports efficient interrupt processing, but dynamic memory allocation and exception processing must be avoided to ensure real-time. 4) Template programming and inline functions help in performance optimization. 5) In practical applications, C can be used to implement an efficient logging system.

To implement loose coupling design in C, you can use the following methods: 1. Use interfaces, such as defining the Logger interface and implementing FileLogger and ConsoleLogger; 2. Dependency injection, such as the DataAccess class receives Database pointers through the constructor; 3. Observer mode, such as the Subject class notifies ConcreteObserver and AnotherObserver. Through these technologies, dependencies between modules can be reduced and code maintainability and flexibility can be improved.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT
