JavaRush /Java Blog /Random-IT /Generazione di una stringa di lunghezza fissa
ttt
Livello 30
Симферополь

Generazione di una stringa di lunghezza fissa

Pubblicato nel gruppo Random-IT
Buon pomeriggio a tutti! Avevo bisogno di scrivere una funzione che generasse una stringa di lunghezza fissa. In realtà, a prima vista è semplice, è così, ma c'era il desiderio di rendere questa funzione il più veloce possibile. E poi è sorta la domanda: come? In realtà ho creato questo codice. Il metodo più veloce finora è generateString, ma credo che possa essere accelerato ancora di più. 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(); } }
Commenti
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION