muecho
2018-07-26 12:50
public class CollectionsTest { public int length; public static final String ALLCHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /** * 1.通过Collections.sort()方法,对Integer泛型的List进行排序; * 创建一个Integer泛型的List,插入十个100以内的不重复随机整数, * 调用Collections.sort()方法对其进行排序 */ public void testSort1(){ List<Integer> integerList = new ArrayList<Integer>(); // 插入十个100以内的不重复随机整数 Random random = new Random(); Integer k; for(int i=0;i<10;i++){ do{ k = random.nextInt(100); }while (integerList.contains(k)); integerList.add(k); System.out.println("成功添加整数:"+k); } 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.对String泛型的List进行排序; * 创建String泛型的List,添加三个乱序的String元素, * 调用sort方法,再次输出排序后的顺序 */ public void testSort2(){ List<String> stringList = new ArrayList<String>(); // 插入十个100以内的不重复随机整数 Random random = new Random(); for(int i=0;i<10;i++){ StringBuffer buf = new StringBuffer(); length = random.nextInt(10) + 1; do{ for(int j=0;j<length;j++){ int number = random.nextInt(ALLCHAR.length()); buf.append(ALLCHAR.charAt(number)); } }while(stringList.contains(buf.toString())); stringList.add(buf.toString()); System.out.println("成功添加元素:" + buf); } System.out.println("-------排序前-------"); for (String str:stringList ) { System.out.println("元素:"+str); } Collections.sort(stringList); System.out.println("-------排序后-------"); for (String str:stringList ) { System.out.println("元素:"+str); } } /** * 3.对其他类型泛型的List进行排序,以Student为例。 */ public void testSort3(){ List<Student> studentList = new ArrayList<Student>(); List<String> stringList = new ArrayList<String>(); Random random = new Random(); String strnum; for(int i=0;i<3;i++){ int number = random.nextInt(1000); do{ strnum = Integer.toString(number); }while (stringList.contains(strnum)); stringList.add(strnum); } studentList.add(new Student(stringList.get(0),"tom")); studentList.add(new Student(stringList.get(1),"jack")); studentList.add(new Student(stringList.get(2),"jerry")); System.out.println("--------排序前--------"); for (Student stu: studentList ) { System.out.println("学生的姓名为:"+stu.getName()+",学生的ID为:"+stu.getId()); } Collections.sort(studentList); System.out.println("--------排序后--------"); for (Student stu: studentList ) { System.out.println("学生的姓名为:"+stu.getName()+",学生的ID为:"+stu.getId()); } System.out.println("--------使用comparator排序--------"); Collections.sort(studentList,new StudentComparator()); for (Student stu: studentList ) { System.out.println("学生的姓名为:"+stu.getName()+",学生的ID为:"+stu.getId()); } } public static void main(String[] args) { CollectionsTest ct = new CollectionsTest(); //ct.testSort1(); // ct.testSort2(); ct.testSort3(); } }
针对课后作业写了一下testSort2()方法和testSort3()方法。
Java入门第三季
409788 学习 · 4340 问题
相似问题