手记

随机产生十条字符串并排序

package com.chris.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class TestContainsSort {

public static void main(String[] args) {
    // TODO Auto-generated method stub
    TestContainsSort tcs=new TestContainsSort();
    tcs.testSort();

}

public void testSort(){
    List<String> stringList=new ArrayList<String>();
    // ASCII中:数字(48~57)大小字母(65~90)小写字母(97~122)
    String str;
    for(int t=0;t<10;t++){
        Random random=new Random();
        int size;
        do{
             size=random.nextInt(10);
        }while(size<1);
        char []chararray=new char[size];
        for(int i=0;i<size;i++){            
            char ch;
            int num;
            do{
                 num=random.nextInt(122);
            }while(num<48||(num>57&&num<65)||(num>90&&num<97));         
            ch=(char) num;
            chararray[i]=ch;
        }
        str=String.valueOf(chararray);
        System.out.println("添加的字符串:"+str);
        stringList.add(str);
    }       
    System.out.println("------------排序前-------------");
    for (String string : stringList) {
        System.out.println(string);     
    }
    System.out.println("------------排序后-------------");
    Collections.sort(stringList);//Collection.sort(stringList);
    for (String string : stringList) {
        System.out.println(string);     
    }

}

}

2人推荐
随时随地看视频
慕课网APP