0

So every time I run the method test my String array is added to my ArrayList and it will print out the lyricLineInfo[4] value, but when the method test is ran again the array will be added on to the ArrayList but it will also replace all of the other ArrayList values with the new array. So when lyricLineInfo[4] is printed again it prints the new value instead of the old value like it's suppose to. I'm not sure why it's doing this can anyone help? Here is my code:

private String[] lyricLineInfo = new String[5];
private ArrayList<String[]> lyricLineNumber = new ArrayList<String[]>();

public void test() {
    lyricLineNumber.add(getInfo());
    System.out.println(lyricLineNumber.get(0)[4])
}

public String[] getInfo() {
    if (chckbxLeadSinger.isSelected()) {
        lyricLineInfo[0] = "true";
    } else {
        lyricLineInfo[0] = "false";
    }
    if (chckbxBackupSinger.isSelected()) {
        lyricLineInfo[1] = "true";
    } else {
        lyricLineInfo[1] = "false";
    }
    lyricLineInfo[2] = fieldStartTime.getText();
    lyricLineInfo[3] = fieldEndTime.getText();
    lyricLineInfo[4] = fieldLyrics.getText();
    return lyricLineInfo;
}

2 Answers 2

6

You're only creating one lyricLineInfo. It shouldn't be a field but a local variable created inside the getInfo() method.

That is to say, remove the line

private String[] lyricLineInfo = new String[5];

and add

String[] lyricLineInfo = new String[5];

as the first line in your getInfo() method.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 as this is correct AFAIK, but it would be better if you elaborate.
@Binyamin Sharet - I had saved a partial edit and was elaborating a bit as you wrote this.
1

You're adding a POINTER to the array to the array list, not a COPY of it. So when you change the array, it changes what you appear to have in the array list.

Try

public void test()
{
    String[] temp = new String[5];
    temp = getInfo();
    lyricLineNumber.add(temp);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.