问答详情
源自:6-5 应用 Collections.sort() 实现 List 排序

课后习题,仅供参考。

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Random;


public class CollectionsTest {


public void testSort1(){

List<Integer> integerList = new ArrayList<Integer>();

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("-----------Before Sorting--------");

for(Integer integer: integerList){

System.out.println(integer);

}

Collections.sort(integerList);

System.out.println("-----------After Sorting---------");

for(Integer integer: integerList){

System.out.println(integer);

}

}

public void testSort2(){

List<String> stringList = new ArrayList<String>();

stringList.add("Apple");

stringList.add("Microsoft");

stringList.add("Google");

System.out.println("-------Before Sorting-------");

for(String string: stringList){

System.out.println(string);

}

Collections.sort(stringList);

System.out.println("-------After Sorting-------");

for(String string: stringList){

System.out.println(string);

}

}

public void testSort3(){

List<String> integerList = new ArrayList<String>();

String string = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";

Random random = new Random();

for(int i=0; i<10; i++ ){

String str = "";

do{

int a = random.nextInt(string.length());

for(int j=0; j<a; j++){

int k = random.nextInt(string.length());

char m = string.charAt(k);

str = str + m; 

}

}while (integerList.contains(str));

integerList.add(str);

}

System.out.println("-----------Before Sorting--------");

for(String str: integerList){

System.out.println(str);

}

Collections.sort(integerList);

System.out.println("-----------After Sorting---------");

for(String str: integerList){

System.out.println(str);

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub


CollectionsTest ct = new CollectionsTest();

// ct.testSort1();

// ct.testSort2();

ct.testSort3();

}


}



提问者:慕仰0416732 2015-11-22 05:15

个回答

  • Perona
    2015-11-24 19:45:16

    谢谢~~