You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.
package com.utils ;
import java.util.Random ;
public class CommonUtil {
/**
* 此静态方法用于生成一个指定长度的随机字符串,可应用于需要生成随机标识、临时验证码等场景,通过传入参数来控制生成字符串的长度。
*
* @param num 用于指定要生成的随机字符串的长度, 参数类型为Integer, 即传入一个整数, 该整数决定了最终生成的随机字符串包含多少个字符。
* @return 返回值类型为String, 即返回一个按照特定规则生成的随机字符串, 其字符内容来源于预定义的字符集合, 长度由传入的参数num决定。
*/
public static String getRandomString ( Integer num ) {
// 定义一个包含所有可用字符的基础字符串,这里包含了小写英文字母和数字,后续将从这些字符中随机选取来组成最终的随机字符串。
String base = "abcdefghijklmnopqrstuvwxyz0123456789" ;
// 创建一个Random类的实例, 用于生成伪随机数, 它将作为选取字符的随机索引依据, 通过其nextInt方法来获取在指定范围内的随机整数。
Random random = new Random ( ) ;
// 创建一个StringBuffer对象, 用于高效地拼接字符, 相比于直接使用字符串相加操作, StringBuffer在频繁拼接字符时性能更好, 将逐步把随机选取的字符添加到这里来构建最终的随机字符串。
StringBuffer sb = new StringBuffer ( ) ;
// 通过循环来控制生成的随机字符串的长度, 循环次数由传入的参数num决定, 每次循环向字符串中添加一个随机字符。
for ( int i = 0 ; i < num ; i + + ) {
// 生成一个随机索引, 其范围是从0到base字符串的长度减1( 通过调用Random类的nextInt方法实现) , 该索引将用于从base字符串中选取一个字符。
int number = random . nextInt ( base . length ( ) ) ;
// 根据生成的随机索引, 从base字符串中获取对应的字符, 并添加到StringBuffer对象sb中, 逐步构建随机字符串。
sb . append ( base . charAt ( number ) ) ;
}
// 将StringBuffer对象转换为字符串并返回, 得到最终生成的随机字符串, 其长度和字符内容都符合随机生成的要求, 由上述逻辑决定。
return sb . toString ( ) ;
}
}