0

I want to random 5 values in my arraylist < BigInteger >.

I will first ask for a input for a value. the value can be from 1-∞.

I realized a problem with code is that, if I enter a value >= 500000, the program will start to throw heap space error. How can I resolve this?

public static void main(String[] args) {
    BigInteger p;
    p = readBigInteger("Enter a value ");
    ArrayList<BigInteger> list = new ArrayList<BigInteger>();

    for (BigInteger bi = BigInteger.valueOf(1); bi.compareTo(p) <= 0; bi = bi.add(BigInteger.ONE)) {
        list.add(bi);
    }
    Collections.shuffle(list);

    for (BigInteger bi = BigInteger.valueOf(1); bi.compareTo(new BigInteger("5")) <= 0; bi = bi.add(BigInteger.ONE)) {
        Integer a = bi.intValue();
        System.out.println(list.get(a));
    }
}   
user2935569
  • 347
  • 2
  • 7
  • 15
  • >> I will first ask for a input for a value. the value can be from 1-∞. do you really thing bigint, or whatever... can reach to `∞` – mlwn Nov 09 '14 at 23:29
  • @mlvn I am not really sure what is the max it can reach. sorry about that – user2935569 Nov 09 '14 at 23:30
  • Edit: You are just running out of memory because you are putting each biginteger between 0 and `p` in a list. – SJuan76 Nov 09 '14 at 23:33

2 Answers2

2

Basically you are creating as many BigInteger objects as the user inputs. So, if the user provided 500000 as an input, there will be so many BigIntegers. They are consuming space in the heap of your program (the heap is the storage of all your objects). The problem is, that this storage is limited and the JVM will cancel your program if there is no space left. You could try making the heap bigger with a JVM command. But do you REALLY need to store all those BigIntegers? Probably not.

Philipp Murry
  • 1,660
  • 9
  • 13
  • 1
    Or do not store them at all, because there is little merit in knowing that the 123,456th integer is 123,456... – SJuan76 Nov 09 '14 at 23:37
  • you're right, i edited my comment. while writing i forgot that the numbers provide no information at all – Philipp Murry Nov 09 '14 at 23:38
0

So you want to get 5 random numbers within the specified range? Use the method here and call it 5 times.

Community
  • 1
  • 1
Enno Shioji
  • 26,542
  • 13
  • 70
  • 109