1

Problem is I have a text file I need to read that contains chars and I need to construct that into an 2D array internally in a class. But since when I initialize I also have to specify the values like so:

int[] array;
array = new int[] {2, 7, 9};

Since I don't know the size of the array before I read the file, I am able to create one as a member, but as a local one only. As of this, I resorted to using arrayLists, which is not desirable. Am I missing something?

Thanks.

Senethys
  • 65
  • 9
  • 1
    an arraylist is designed specifically for this reason, when the total size of your collection is unknown. What's wrong with creating an arraylist of arraylists? it's equivalent to a 2D array but more flexible – RAZ_Muh_Taz Jun 13 '18 at 20:27
  • wow, I did not know this. To answer your question, it's slow (not that it matters but it might) and I honestly find the syntax of a 2d arraylist more confusing than 2d arrays although it is more flexible as you say. That is basically it. @RAZ_Muh_Taz – Senethys Jun 13 '18 at 20:32

2 Answers2

2

ArrayList would be the best option for this problem because the size of the ArrayList is mutable, meaning that no matter the size of the data, it will always change it's size to match the amount of elements it contains.

Here's more detail on creating and using 2D ArrayLists.

Hope this helps.

1
List<Integer> array = new ArrayList<>();

array.add(2);
array.add(7);
array.add(9);

OR prior to Java 9:

List<Integer> array = new ArrayList<Integer>(Arrays.asList(2,7,9));
array.add(10);

OR in Java 9:

List<Integer> array = List.of(2,7,9);
Pavel Molchanov
  • 2,299
  • 1
  • 19
  • 24