码迷,mamicode.com
首页 > 编程语言 > 详细

java随机生成字符串并排序

时间:2015-08-13 11:21:05      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.Imooc;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collections;
 5 import java.util.List;
 6 import java.util.Random;
 7 
 8 /**
 9  * 利用Collections.sort()方法对泛型为String的List进行排序
10  * 1. 创建List<String>之后往其中添加十条随机字符串
11  * 2. 每条字符串为10以内的随机数
12  * 3. 每条字符串的每个字符的每个字符都为随机生成的字符串。字符可以重复
13  * 4. 每条随机字符串不可以重复
14  * @author WYL
15  *
16  */
17 public class StringSortVersion2 {
18 
19     //首先创建一个String的泛型
20     List<String> stringList = new ArrayList<String>();
21     
22     public void stringSort(){
23         Random random = new Random();
24         String str;
25         for(int i=0;i<10;i++){
26             int stringLength = random.nextInt(10);
27             do{
28                 //调用自定义函数随机生成字符串
29                 str = randomString(stringLength);
30             }while(stringList.contains(str));
31             System.out.println("将要添加的字符串: ‘"+str+"‘");
32             stringList.add(str);
33         }
34         System.out.println("*************排序前的字符串**************");
35         
36         for(String string:stringList){
37             System.out.println("元素:"+string);
38         }
39         
40         Collections.sort(stringList);
41         System.out.println("***************排序后的字符串**************");
42         for(String string: stringList){
43             System.out.println("元素:"+string);
44         }
45     }
46     
47     /**
48      * 生成随机字符串函数
49      * @param args
50      */
51     public String randomString(int length){
52         String string = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
53         Random random = new Random();
54         StringBuffer str = new StringBuffer();
55         for(int i = 0; i < length;i++ ){
56             //随机获取字符串(string)长度的的一个值,为生成字符串做准备
57             int index = random.nextInt(62);
58             str.append(string.charAt(index));
59         }
60         //返回字符串
61         return str.toString();
62     }
63     public static void main(String[] args) {
64         // TODO Auto-generated method stub
65 
66         StringSortVersion2 ss = new StringSortVersion2();
67         ss.stringSort();
68     }
69 
70 }

 

java随机生成字符串并排序

标签:

原文地址:http://www.cnblogs.com/blogofwyl/p/4726384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!