貼一下自己代碼,看有木有要改進的地方
package com.imooc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CollectionsTest {
?? ?
??? public void testRandomStringSort(){
?? ??? ?String az09 = "0123456789QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm";
?? ??? ?List<String> stringList = new ArrayList<String>();
?? ??? ?Random rd= new Random();
?? ??? ?for(int i=0;i<10;i++){
?? ??? ??? ?int strLength = rd.nextInt(9)+1;
?? ??? ??? ?String strRandom = "";
?? ??? ??? ?do{
?? ??? ??? ??? ?strRandom = "";
?????? ??? ??? ?for(int j=0;j<strLength;j++){
?????? ??? ??? ??? ?int num = rd.nextInt(az09.length());
?????? ??? ??? ??? ?strRandom += az09.charAt(num);
?????? ??? ??? ?}?? ?
?? ??? ??? ?}while(stringList.contains(strRandom));
?? ??? ??? ?stringList.add(strRandom);
?? ??? ??? ?System.out.println("成功添加:"+strRandom);
?? ??? ?}
?? ??? ?System.out.println("——————排序前————————");
?? ??? ?Collections.sort(stringList);
?? ??? ?for(String str:stringList){
?? ??? ??? ?System.out.println("元素:"+str);
?? ??? ?}
?? ??? ?
??? }
?? ?public static void main(String[] args) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ?CollectionsTest clt = new CollectionsTest();
?? ??? ?
?? ??? ?clt.testRandomStringSort();
?? ?}
}
2016-02-10
????public?static?String?randomString(int?length){ ????????StringBuilder?sb?=?new?StringBuilder(length); ????????for(int?i=0;i<length;i++){ ????????????sb.append((char)(ThreadLocalRandom.current().nextInt(33,128))); ????????} ????????return?sb.toString(); ????} ???? ????public?void?testSort2(){ ????????List<String>?stringList?=?new?ArrayList<String>(); ????????Random?random?=?new?Random(); ????????System.out.println("----preSort-----"); ????????String?k; ????????for(int?i=0;i<10;i++){ ????????????do{ ????????????????k=randomString(random.nextInt(11)); ????????????????System.out.println("Element:"+k); ????????????}while(stringList.contains(k)); ????????} ????????Collections.sort(stringList); ????????System.out.println("----postSort-----"); ????????for(String?string:?stringList){ ????????????System.out.println("Element:"+string); ????????} ????}2016-01-30
????????????????Random?number?=?new?Random(); int?length; do{ length?=number.nextInt(11);//規定1-10?的長度,返回一個1-10的其中一個數 }while(length?==0); //可以考慮改進的地方 //可以就是把字符都塞進去一個List中,就不用自己這么麻煩2016-01-21
?int strLength = rd.nextInt(9)+1;這個就相等于?int strLength = rd.nextInt(10); 隨機數包括0但不包括10,其他的和我的差不多
(。?`ω′?)