How do I make it unique when generating random alphanumeric values in Spring?

Viewed 19

I want to write a method that generates the following url output. Url information will be entered at the end /? After adding a random unique value will be generated and combined and it will be in the following format. The output I want is like this :

I have two big problems here. Firstly, when I want to produce something like 100, www.stackoverfloww.com/? It can remain in the form without producing any unique value and it produces the same value more than once, so the unique condition is broken.

public class quick {
        static List<Character> letters = Arrays.asList('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9');
        static Random r = new Random();
        public static String[] urlGen(String baseUrl, int n) {
            String[] list = new String[n];
            for (String string : list) {
                string = baseUrl + "/?" ;
                for (int i = 0; i < r.nextInt(16); i++) {
                    string +=  letters.get(r.nextInt(35));
                }
                System.out.println(string);
            }
            return null;
        }
        public static void main(String[] args) {
            urlGen("www.stackoverfloww.com", 7);
        }

When I revise the code as below, it does not terminate and takes too long, how can I change it to be fast and unique?

public class quick {
    static List<Character> letters = Arrays.asList('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','1','2','3','4','5','6','7','8','9');
    static Random r = new Random();
    public static String[] urlGen(String baseUrl, int n) {
        String[] list = new String[n];
        for (int i = 0; i < list.length; i++) {
            String s = baseUrl + "/?" ;
            for (int i1 = 0; i1 < r.nextInt(11)+4; i1++) {
                s +=  letters.get(r.nextInt(35));
            }
            if(!arrayContains(list, s)) {
                list[i] = s;
                System.out.println(s);
            } else {
                i--;
            }
        }
        return null;
    }
    
    public static boolean arrayContains(String[] list, String s) {
        for (int i = 0; i < list.length; i++) {
            if(s.equals(list[i])) return true;
        }
        return false;
    }
    
    public static void main(String[] args) {
        urlGen("www.stackoverfloww.com", 7);
    }
}
0 Answers
Related