How can I produce unique values of Object via Random Process in Java

Viewed 90

I want to produce unique values of Movie Object via Random. I wrote a code snippet but I'm not sure all values cannot be unique by using Random().

How can I do this process to produce all of these unique values?

Here is my code snippets shown below.

private static ArrayList<Movie> addMovies(ArrayList<Movie> movieList) {

        for(int i=0;i<20;i++) {
            Movie movie = new Movie();
            movie.setId(defineMovieId());
            movie.setTitle(defineMovieName(15));
            movieList.add(movie);
        }       

        return movieList;
    }


    public static String defineMovieName(int n) { 

        // chose a Character random from this String 
        String AlphaNumericString = "ABCÇDEFGHIİJKLMNOÖPQRSŞTUÜVWXYZ"
                                    + "abcçdefghıijklmnoöpqrsştuüvxyz"; 

        StringBuilder sb = new StringBuilder(n); 

        for (int i = 0; i < n; i++) { 

            int index 
                = (int)(AlphaNumericString.length() 
                        * Math.random()); 

            sb.append(AlphaNumericString 
                          .charAt(index)); 
        } 

        return sb.toString(); 
    } 

    public static long defineMovieId() {
        int max = 1000;
        int min = 1;
        int range = max - min + 1;
        int res = (int) ( Math.random()*range) + min;
        return res; 
    }
2 Answers

The methods which you have defined do not guarantee random IDs or random names. For guaranteed unique values, you can do the following:

  1. For unique ID: create a static variable of AtomicLong type and use getAndIncrement()
  2. For unique names: use UUID.randomUUID()

    Demo:

    import java.util.UUID;
    import java.util.concurrent.atomic.AtomicLong;
    
    public class Main {
        static final long INITIAL_VALUE = 1000000;
        static AtomicLong atomicLong = new AtomicLong(INITIAL_VALUE);
    
        public static void main(String[] args) {
            // Tests
            System.out.println("10 random IDs:");
            for (int i = 1; i <= 10; i++) {
                System.out.print(defineMovieId() + " ");
            }
    
            System.out.println();
    
            System.out.println("10 random movie names:");
            for (int i = 1; i <= 10; i++) {
                System.out.print(defineMovieName() + " ");
            }
        }
    
        public static long defineMovieId() {
            return atomicLong.getAndIncrement();
        }
    
        public static String defineMovieName() {
            return UUID.randomUUID().toString().replace("-", "");
        }
    }
    

    Output:

    10 random IDs:
    1000000 1000001 1000002 1000003 1000004 1000005 1000006 1000007 1000008 1000009 
    10 random movie names:
    0c77d209fb624415af7100c3184b35a6 1262e50b680f4a738a607ff757f2b510 7b93c73d93b34db88fc99d1096c1ce84 cbb9c6c90fb8489dbd9c52d4ebdc2ca3 9ba1d409b32b4c55a7562d714aadc220 ec40b647f33a4fc6becc8c5741eb8bf7 c1fbb7bb77d1417c86c2064039f62dec 82b52fdae1d24602b5ee9becd73ba3ce 2d82d481282b4684b55c168e9d216f36 27b02bf63b054d32a0e43992a5fcb124 
    

Random is not generate a series of unique numbers, just if get lucky.
Better use a static int field for id and increase it each time you need a new id.

//classes names are obvious fake since there are not any random involved, just an example
public class TestRandom {
static int id=0;
public static void main(String[] args)
{
    TestRandom tr = new TestRandom();
    RandomIdObj ro1 = tr.new RandomIdObj(tr.getNextId(),"obj_1");
    RandomIdObj ro2 = tr.new RandomIdObj(tr.getNextId(),"obj_2");
    System.out.println(ro1);
    System.out.println(ro2);
}
public int getNextId()
{
    return ++id;
}

    class RandomIdObj
    {
        int id;
        String name;
        RandomIdObj(int id,String name)
        {
            this.id =id;
            this.name = name;
        }

        public String toString()
        {
            return this.id+":"+this.name;
        }
    }
}

Output:

[unique_id,obj_name]
1:obj_1
2:obj_2
Related