package com.imooc; import java.util.ArrayList; import java.util.Collections; import java.util.Random; public class CollectionSort { ArrayList<String> RandomList = new ArrayList<String>(); /** * 向ArrayList中添加字符串 */ public void addList() { String str; for (int i = 0; i < 10; i++) { do { str = getString(); } while (RandomList.contains(str)); RandomList.add(str); System.out.println("成功添加:"+str); } } /** * 排序 */ public void sortCollection() { System.out.println("--------排序前--------"); for (String string : RandomList) { System.out.println("随机数列:"+string); } System.out.println("--------排序后--------"); Collections.sort(RandomList); for (String string : RandomList) { System.out.println("随机数列:"+string); } } /** * 生成长度10以内的随机字符串 * @return */ public String getString() { Random random = new Random(); String str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRST"; StringBuilder sb = new StringBuilder(); int length = str.length(); do { int ran = random.nextInt(length); sb.append(str.charAt(ran)); } while (sb.length() < random.nextInt(10)); return sb.toString(); } //生成3个1000以内的不重复的数字 public void third(){ int i = 1; Random random = new Random(); int[] id =new int[3]; id[0]=random.nextInt(1000); while(i<3){ if(id[i] != random.nextInt(1000)){ id[i] = random.nextInt(1000); }else{ continue; } i++; } for (int j : id) { System.out.println(j); } } public static void main(String[] args) { CollectionSort cs = new CollectionSort(); cs.addList(); cs.sortCollection(); // cs.third(); } }
楼主,你的third()方法好像有点问题...你把代码中的“1000”改为“10”,运行会出现重复数字!