JavaRush /Blog Java /Random-FR /Générer une chaîne de longueur fixe
ttt
Niveau 30
Симферополь

Générer une chaîne de longueur fixe

Publié dans le groupe Random-FR
Bonjour à tous ! J'avais besoin d'écrire une fonction qui générait une chaîne de longueur fixe. En fait, à première vue, c'est simple, c'est comme ça, mais il y avait une volonté de rendre cette fonction aussi rapide que possible. Et puis la question s'est posée : comment ? En fait, j'ai construit ce code. La méthode la plus rapide jusqu'à présent est generateString, mais je pense qu'elle peut être encore plus accélérée. public class StringGenerator{ private int strLength; private StringGenerator() { } public static StringGenerator getStringFixedLengthGenerator(int length){ StringGenerator stringGenerator = new StringGenerator(); stringGenerator.setStrLength(length); return stringGenerator; } public void setStrLength(int strLength) { this.strLength = strLength; } public String generateNextFixedString(){ return new String(); } public String generateThreadString() { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable task = () -> { return generateString(strLength/2); }; Future future = executor.submit(task); Future future1 = executor.submit(task); String str = ""; try{ str = future1.get().concat(future.get()); }catch (Exception e){ } executor.shutdown(); return str; } public String generateString(){ return generateString(strLength); } public String generateString(int stringLength) { String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; Random rng = new Random(); char[] text = new char[stringLength]; for (int i = 0; i < stringLength; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } public String createRandomString() { String mCHAR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; int STR_LENGTH = strLength; // длина генерируемой строки Random random = new Random(); StringBuilder builder = new StringBuilder(); for (int i = 0; i < STR_LENGTH; i++) { int number = random.nextInt(mCHAR.length()); char ch = mCHAR.charAt(number); builder.append(ch); } return builder.toString(); } }
Commentaires
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION