package com.imooc.collection;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;public class TestCollectionsSortString { /** * 生成随机字符串 * @param length * @return */ public String getRandomString(int length) { String str ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random=new Random(); StringBuffer sb=new StringBuffer(); for(int i=0;i<length;i++){ //产生62以内的随机数,因为组成随机字符串的字符有62个 int number=random.nextInt(62); //将str的第number个字符加到sb的末尾 sb.append(str.charAt(number)); } return sb.toString(); } /** * 让随机字符串的长度为10以内随机整数,并进行排序输出 */ public void testSort() { List<String> stringList = new ArrayList<String>(); Random random = new Random(); int k; String str; for(int i=0;i<10;i++) { k = random.nextInt(10); do { str=getRandomString(k); }while(stringList.contains(str)); stringList.add(str); System.out.println("成功添加:"+str); } 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); } } public static void main(String[] args) { TestCollectionsSortString tcss = new TestCollectionsSortString(); tcss.testSort(); }}
太乱了,小哥哥