火柴火财
2022-03-10 17:57
/** * 创建String泛型的List,放入10条随机的字符串 * 每条字符串的长度为10以内的随机整数 * 每条字符串的字符都是随机生成的字符,可以重复 * 每条随机生成的字符串不可以重复 **/ public void testStringSort3() { List<String> stringList = new ArrayList<>(); Random random = new Random(); int k; String str; for (int i=0;i<10;i++) { do { k = random.nextInt(10); str = this.getRandomString(k); }while (stringList.contains(str) || str.equals("")); stringList.add(str); } System.out.println("---------排序前----------"); for (String i:stringList) { System.out.println("元素:"+i); } System.out.println("---------排序后----------"); Collections.sort(stringList); for (String i:stringList) { System.out.println("元素:"+i); } } /** * 返回字符串 * @param length 长度 * @return Sting */ private String getRandomString(int length) { String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuilder stringBuffer = new StringBuilder(); Random random = new Random(); for (int i=0;i<length;i++) { stringBuffer.append(str.charAt(random.nextInt(str.length()))); } return stringBuffer.toString(); } public static void main(String[] args) { CollectionsTest collectionsTest = new CollectionsTest(); // collectionsTest.testSort1(); collectionsTest.testStringSort3(); }
/** * 对String泛型的List进行排序 */ public void testSortSring() { List<String> StringList = new ArrayList<String>(); // 插入十个10以内的不重复随机整数 Random random=new Random(); int k ; String str; for (int i = 0; i < 10; i++) { do { k=random.nextInt(10); str= this.getRandomSting(k); } while (StringList.contains(str)||str==""); StringList.add(str); System.out.println("成功添加字符串:" + str); } System.out.println("-------------排序前--------------"); for (String i: StringList) { System.out.println("元素:" + i); } Collections.sort(StringList); System.out.println("----------------排序后-------------------"); for (String i: StringList) { System.out.println("元素:" + i); } } /** * 返回随机字符串 */ private String getRandomSting(int length) { String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; StringBuilder stringBuilder = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { stringBuilder.append(str.charAt(random.nextInt(str.length()))); } return stringBuilder.toString(); }
Java入门第三季
409792 学习 · 4340 问题
相似问题