package test;
import java.util.*;
public class TestSort {
// 随机生成长度小于输入值的字符串
public String getRandomString(int length) {
// 生成一个随机数
Random random = new Random();
StringBuffer str = new StringBuffer();
// 循环length次
for (int i = 0; i < length; i++) {
int number = random.nextInt(4);
long result = 0;
// 随机选择空值、数字或大小写字母
switch (number) {
case 0:
result = Math.round(Math.random() * 25 + 65);
str.append(String.valueOf((char) result));
break;
case 1:
result = Math.round(Math.random() * 25 + 97);
str.append(String.valueOf((char) result));
break;
case 2:
str.append(String.valueOf(new Random().nextInt(10)));
break;
case 3:// 空值
break;
}
}
return str.toString();
}
public void stringTest() {
List<String> stringList = new ArrayList<String>();
TestSort t = new TestSort();
// 随机生成10个字符串
for (int i = 0; i < 10; i++) {
String str = t.getRandomString(10);
stringList.add(str);
System.out.println("新增字符串:" + str);
}
System.out.println("-------------------排序前-------------------");
for (int i = 0; i < 10; i++) {
System.out.println(stringList.get(i));
}
Collections.sort(stringList);
System.out.println("-----------------排序后----------------");
for (int i = 0; i < 10; i++) {
System.out.println(stringList.get(i));
}
}
public static void main(String[] args) {
TestSort test = new TestSort();
test.stringTest();
}
package com.imooc.collection; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * 2021-3-29 * 1.创建List<String>之后,往其中添加十个随机字符 * 2.每个随机字符串得长度为10以内得整数 * 3.每条字符串得每个字符都为随机生成得字符,字符可以重复 * 4.每条随机字符串不可重复 */ //原来需要在main方法里面 构造输出 public class RandomWords { public static void main(String[] args) { List<String> stringList = new ArrayList<String>(); Random random = new Random(); List<Integer> integerList = new ArrayList<Integer>(); String contaniner = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Integer k; System.out.println("现在输出随机10个字符串的长度:"); //现得到10个随机字符串得长度 并且得到得每一个字符串得长度都不相等 for (int i = 0; i < 10; i++) { do { k = random.nextInt(10)+1; } while (integerList.contains(k)); integerList.add(k); } for (Integer I : integerList) { System.out.print("元素" +(integerList.indexOf(I)+1)+"长度:"+ I+ " "); } for (int j = 0; j < 10; j++) { StringBuffer string = new StringBuffer(); do { for (int z = 0; z < integerList.get(j); z++) { int num = random.nextInt(61); string.append(contaniner.charAt(num)); } } while (stringList.contains(string)); String Str=string.toString(); stringList.add(Str); } //输出随机字符串 System.out.println("输出10个随机字符串"); System.out.println("---------------------排序前---------------"); for (String strings : stringList) { System.out.println("元素:" +strings); } Collections.sort(stringList); System.out.println("---------------------排序后---------------"); for (String strings : stringList) { System.out.println("元素:" + strings); } } }