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

交个作业~~~

package 学生选课;


import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.Random;


//练习

//对String泛型的List进行排序,创建String泛型的List,添加三个乱序的String元素,调用Collection.sort()方法排序2-2


public class Practice {


String allString = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

public void testSort() {

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

Random random = new Random();

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

StringBuilder sbu = new StringBuilder();

int length = random.nextInt(10) + 1;

do {

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

int number = random.nextInt(allString.length());

sbu.append(allString.charAt(number));


}

}while(stringList.contains(sbu.toString()));

stringList.add(sbu.toString());

System.out.println("成功添加元素:" + sbu);

}

System.out.println("--------排序前--------");

for (String s : stringList) {

System.out.println("元素:" + s);

}

Collections.sort(stringList);

System.out.println("--------排序后--------");

for (String s : stringList) {

System.out.println("元素:" + s);

}

}

public static void main(String[] args) {

Practice p = new Practice();

p.testSort();

}

}


提问者:YGT_郁子 2018-08-15 14:55

个回答

  • 低調d華麗
    2018-08-30 09:23:05

    其中  int number = random.nextInt(allString.length());

    sbu.append(allString.charAt(number));  只是取了字符串中一个字符