慕粉1922375890
2020-05-26 23:38
package basedknowledge.sortTestt; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * @Description: * 创建String泛型的List,放入10条随机的字符串 * 每条字符串的长度为10以内的随机整数 * 每条字符串的字符都是随机生成的字符,可以重复 * 每条随机生成的字符串不可以重复 * @Author zhiming * @Date 2020/5/26 22:34 **/ public class sortTest { public List<String> ls = new ArrayList(); public String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678"; Random randomInt = new Random(); Integer k; /* * @Description: 生成一个符合要求的序列 * @Param: **/ public List<String> creatList(){ for (int i=0; i<10; i++){ StringBuffer sb = new StringBuffer(); do { k = randomInt.nextInt(10); for (int j=0; j<k+1; j++){ sb.append(str.charAt(randomInt.nextInt(str.length()))); } }while (ls.contains(sb)); ls.add(sb.toString()); } return ls; } public void sort(List ls){ System.out.println("-----------排序前输出:-----------"); for(Object str:ls){ System.out.println(str); } Collections.sort(ls); System.out.println("-----------排序后输出:-----------"); for(Object str:ls){ System.out.println(str); } } public static void main(String[] args) { sortTest st = new sortTest(); st.sort(st.creatList()); } }
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); } } }
Java入门第三季
409792 学习 · 4340 问题
相似问题