-4

I am reading input from a file (filename provided as command line argument) containing an unknown number of integers. The custom 'readInts' method will read the integers and return an array. I do not know about the size of the array to initialize it in the beginning.

The class containing the 'readInts' method- https://algs4.cs.princeton.edu/code/edu/princeton/cs/algs4/In.java.html

int []whitelist;
if(args.length>0) {
    whitelist = In.readInts(args[0]);
}
Arrays.sort(whitelist);

How do I go about this, since the size of the array is unknown in the beginning? Will there be any memory loss if I create an array of size 'x' in the beginning, and then assign the output of readInts to it?

Karthik Bhat
  • 361
  • 1
  • 4
  • 11
  • 4
    assign a default value, or move the `Arrays.sort()` statement inside the `if`-condition – Lino Jan 25 '19 at 10:15
  • 2
    If `args.length > 0` returns false, whitelist has not been assigned any value. Java complains because how can you sort *nothing*? Assign an empty array or something - exactly what you do will depend on your use-case. See the linked duplicate. – Michael Jan 25 '19 at 10:16
  • Can I use an array list instead? Since I do not know the actual size it might take? – Karthik Bhat Jan 25 '19 at 10:19

1 Answers1

3

That is because whitelist won't be initialized if args.length==0. In this case, Arrays.sort(whitelist); will most likely throw an exception. How to prevent this depends on what you want to do but it seems you'll probably simply not use whitelist at all when not having args:

if(args.length>0) {
    int [] whitelist = In.readInts(args[0]);
    Arrays.sort(whitelist);
}

Or have some kind of default:

int []whitelist=new int[0];
if(args.length>0) {
    whitelist = In.readInts(args[0]);
}
Arrays.sort(whitelist);
Gamification
  • 787
  • 5
  • 20
  • So, I can give a random size to the array now, and later it updates automatically depending on the input read? – Karthik Bhat Jan 25 '19 at 10:25
  • 1
    `whitelist = In.readInts(args[0]);` assigns a completely new array to the identifier. The old array then won't be relevant anymore. `whitelist=new int[0];` wasn't supposed to be *random size* I assumed you might want an empty whitelist as a "default" – Gamification Jan 25 '19 at 10:30