在java中隨機產生一個無序且長度不大於10的字串

來源:互聯網
上載者:User

標籤:--   傳遞   ber   system   package   on()   .so   .com   list   

 

package xiangmu;import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Random;public class TestCollection {    /*     * 通過定義Collections.sort()方法對String泛型進行List排序     * 建立一個String泛型List,插入一個不超過10的隨機字串     */    /**     * @param args     */    public void testSort1(){        List<String> stringList=new ArrayList<String>();                Random random=new Random();        String k="1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";        //添加10個不同的隨機字串        for(int i=0;i<10;i++){            StringBuffer str=new StringBuffer();            int stringLength=random.nextInt(10)+1;            do{                for(int j=0;j<stringLength;j++){                                    int number=random.nextInt(k.length());                str.append(k.charAt(number));                                }            }while(stringList.contains(str.toString()));//調用stringList.contains()方法將字串傳遞進去            stringList.add(str.toString());//將字串加入到stringList中,調用stringList.add()方法            System.out.println("成功添加字串:"+str);        }        System.out.println("----------排序前---------------");        //用foreach進行遍曆        for(String string:stringList){                        System.out.println("元素:"+string);        }        Collections.sort(stringList);//調用Collections.sort()進行排序        System.out.println("----------排序後---------------");        for(String string:stringList){                        System.out.println("元素:"+string);        }            }    public static void main(String[] args) {        // TODO Auto-generated method stub        TestCollection ct=new TestCollection();        ct.testSort1();    }}

在java中隨機產生一個無序且長度不大於10的字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.