JavaRush /Java Blog /Random EN /Generating a Fixed Length String
ttt
Level 30
Симферополь

Generating a Fixed Length String

Published in the Random EN group
Good afternoon everyone! I needed to write a function that generated a fixed-length string. Actually, at first glance it’s simple, that’s the way it is, but there was a desire to make this function as fast as possible. And then the question arose - how? Actually I built this code. The fastest method so far is generateString, but I believe it can be speeded up even more. 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(); } }
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION