I’m looking to create an array that will be able to change size over time because the size of the array is unpredictable and I don’t want to create a huge random number that will waste memory so every time a button is pressed I need the array to grow by one.
private String[][] lyricLineInfo = new String[x][5];
In the place of x is where the array must grow upon the button push and 5 is a constant. So I need the x button to grow by one without overflowing. Can I do it by using something like this?
lyricLineInfo[lyricLineInfo.length + 1][4] = fieldLyrics.getText();
Anyways thanks in advance!
Use an
ArrayList<String[]>(see the docs here). It will grow automatically. (It uses an internal array that doesn’t actually grow by just 1 when it needs to grow. Since growing is an expensive operation, it grows by some larger amount so it can absorb a few more items before having to grow again.)EDIT
For example, here’s how you could recode the two lines of your original post:
The second line assumes that
fieldLyrics.getText()returns aString[]. If I misunderstood your intent and it returns a String, then you could do the following:If the second index isn’t always 5 long, you can also have an ArrayList of ArrayLists:
Then you could
lyricLineInfo.add(new ArrayList<String>());to extend the array.EDIT 2
@clankfan1 – In your comment, you asked how to do a particular operation. Let’s say we’re using the
ArrayList<ArrayList<String>>structure. It would go something like this:Obviously, this logic is amenable to being put into a separate method.
EDIT 3
If you need the elements of
lyricLineInfoto be of typeString[], it is vital that each element be a distinct array. Here are a few coding styles for adding elements: