Home >Java >javaTutorial >Introduction to how to generate a random string array in Java

Introduction to how to generate a random string array in Java

黄舟
黄舟Original
2017-08-10 09:59:394261browse

This article mainly introduces the relevant information about Java's detailed examples of generating random string arrays. It mainly uses the Collections.sort() method to sort the List of generic Strings. Friends who need it can refer to it

Java Detailed Example of Generating a Random String Array

Use the Collections.sort() method to sort a List whose generic type is String. Specific requirements:

1. After creating Listf7e83be87db5cd2d9a8a0b8117b38cd4, add ten random strings to it
2. The length of each string is a random integer within 10
3. Each Each character of the string is a randomly generated character, and the characters can overlap
4. Each random string cannot be repeated

The knowledge involved is: String, StringBuffer, ListArray, Generics, Collections.sort, foreach, Random and other related knowledge can be regarded as a relatively good practice in the JAVA learning process.

1. Randomly generate a character

1.1 First store all letters and numbers 0-9 in a string for subsequent use.


String str = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStT
       uUvVwWxXyYzZ0123456789";

1.2 To satisfy the randomness, create a Random object and use the nextInt(str.length) method to generate a 0 — str.length random number.


Random random = new Random();
int index = random.nextInt(str.length());

1.3 Then use the random number generated above as the index of the str string to retrieve the corresponding character, and randomly generate a character


char c = str.charAt(index);

2. Generate a random string with a length within 10

2.1 Because it is within 10 and meets randomness, here Use the Math.random() function, whose return value is a random Double type number from 0.0 to 1.0


StringBuffer stringBuffer = new StringBuffer();
//确定字符串长度
int stringLength = (int) (Math.random()*10);

2.2 Now the length of the string can be confirmed, and Generate random characters, and then use the for loop to generate a random string with a length of less than 10


for (int j = 0; j < stringLength; j++) {
  int index = random.nextInt(str.length());
  char c = str.charAt(index);
  stringBuffer.append(c);  
 }
//将StringBuffer转换为String类型的字符串
String string = stringBuffer.toString();

3. Generate 10 Random string

3.1 After the above two steps, and then nesting a for loop outside, 10 random strings can be generated

4. Create a ListArrayf7e83be87db5cd2d9a8a0b8117b38cd4 collection to store 10 random strings

4.1 Create a String type collection, this step should be completed simultaneously with Step 3


List<String> listString = new ArrayList<String>();

4.2 Add a string generated each time to the set. Pay attention to using the Contains() method of the set to determine whether the same string already exists in the set (although the probability is very small).


//判断当前的list容器中是否已有刚生成的字符串,满足每条字符串不可重复性
if(!(listString.contains(stringBuffer.toString()))){
   listString.add(stringBuffer.toString());
 }else {
   //i-- 如果不满足则重新生成
  i--;
 }

5 Finally sort the collection

5.1 Call the Collections.sort() method to sort the collection. The rules are as follows:

  • principle from left to right, and 0-9

  • number priority principle, and A-Z

  • Capital letters take precedence, and a-z

##Total code


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

public class RandomString {

  public static void main(String[] args) {
    List strList = randomString();
    System.out.println("------随机生成的10条字符串-------");
    for (String string : strList) {
      System.out.println(string);
    }
    System.out.println("------------排序后------------");
    Collections.sort(strList);
    for (String string : strList) {
      System.out.println(string);
    }  
  }
  public static List randomString(){
    //将所有的大小写字母和0-9数字存入字符串中
    String str = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789";
    Random random = new Random();
    List<String> listString = new ArrayList<String>();
    String strArray[ ] = new String[10];
    //生成10条长度为1-10的随机字符串
    for (int i = 0; i < 10; i++) {
      StringBuffer stringBuffer = new StringBuffer();
      //确定字符串长度
      int stringLength = (int) (Math.random()*10);
       for (int j = 0; j < stringLength; j++) {
         //先随机生成初始定义的字符串 str 的某个索引,以获取相应的字符
        int index = random.nextInt(str.length());
        char c = str.charAt(index);
        stringBuffer.append(c);  
       }
       //判断当前的list容器中是否已有刚生成的字符串,满足每条字符串不可重复性
       if (!(listString.contains(stringBuffer.toString()))) {
         listString.add(stringBuffer.toString());
      }else {
        i--;
      }

    }
    return listString;
  }
}

The output answer is not unique

The above is the detailed content of Introduction to how to generate a random string array in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn