自定类型不能直接排序,因为没有实现Comparable接口
sort()
sort方法 和 Comparable接口
排序 sort
sort排序的元素要实现Comparable接口
80%
studentList.add(new Student(1 + "","小明"));
为什么是这样书写 (1+"")这就是一个字符串啊,数字+""就转成字符串了,等同于"1"。
student不是comparable接口的实现类
所以不能sort(student)
利用Collections.sort()方法对各种类进行排序
对于像Integer这样基本类型的包装类以及String泛型的ListCollections.sort()都是非常管用非常方便的
对于其他泛型元素必须实现Comparable接口
package com.imooc_b;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTset {
public void Sort() {
List<String> listTset = new ArrayList<String>();
Random random = new Random();
// 生成十条不重复的字符串(由数字和字母组成)
for (int i = 0; i < 10; i++) {
StringBuffer buffer = new StringBuffer();
do {
// 字符串长度为10以内的整数,nextInt()范围为(0,9),字符串长度不想设置为空就加1
int k = random.nextInt(9) + 1;
// 随机生成字符串
for (int j = 0; j < k; j++) {
int b;
do {
// 随机生成0到122的数字,0到9表示数字字符,65到90表示'A'到'Z'
// 97到122表示'a'到'z'
b = (int) (Math.random() * 123);
}
// 当生成的字符为'0'到'9'或'a'到'z'或'A'到'Z'时跳出
while (!((b >= 0 && b <= 9) || (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')));
if (b >= 0 && b <= 9) {
String in = Integer.toString(b);
buffer.append(in);
} else {
char ch = (char) b;
String in = String.valueOf(ch);
buffer.append(in);
}
}
} while (listTset.contains(buffer.toString()));
// 如果list没有该字符串就加入
listTset.add(buffer.toString());
}
System.out.println("-------排序前----------");
for (String string : listTset) {
System.out.println("元素:" + string);
}
Collections.sort(listTset);
System.out.println("---------排序后---------");
for (String string : listTset) {
System.out.println("元素:" + string);
}
}
public static void main(String[] args) {
CollectionsTset ct = new CollectionsTset();
ct.Sort();
}
}
studentList.add(new Student(1 + "","小明"));
为什么是这样书写 (1+"")这就是一个字符串啊,数字+""就转成字符串了,等同于"1"。
Collections.sort(studentList);
会报错//Collections.sort()方法,必须有comparable接口
自定义的不能比较
collection.sort()方法对元素进行排序,列表中的元素都必需实现 Comparable 接口,否则不能使用 sort()方法排序
public void testSort3(){ List<Student> studentList=new ArrayList<Student>(); studentList.add(new Student(1+"","小明")); studentList.add(new Student(2+"","小红")); studentList.add(new Student(3+"","小兰")); System.out.println("----排序前-------"); for(Student student:studentList){ SYstem.out.println("学生:"+student.name);} Collections.sort(studentList);}
Collections工具类---sort()
注意点:不能使用自定义的,若要使用则要实现Comparable接口。