Airfix
Airfix

Reputation: 127

Adding Array elements to 2d ArrayList

I'm having trouble adding array elements to an arraylist. I used some old code that I used to put array elements into a 2D array. However when I try to put a string array into my arraylist I get the following error: Array type expected; found: 'java.util.ArrayList<java.lang.String[]>'

I can't figure out how to cast the string into and arraylist object if that's the right thing to be doing?

You can see my code below:

 public void scoresArrayListMethod(){
        InputStreamReader InputSR = null;
        BufferedReader BufferedRdr = null;
        String thisLine = null;

        AssetManager am = getAssets();
        ArrayList<String []> alScores = new ArrayList<>();

        try {
            InputSR = new InputStreamReader(am.open("testdata/test_scores.txt"));
            BufferedRdr = new BufferedReader(InputSR);

            // open input stream test_scores for reading purpose.
            int i = 0;
            while ((thisLine = BufferedRdr.readLine()) != null) {


                String[] parts = thisLine.split(" ");

                alScores.addAll(parts); // Tried this with no joy
                alScores[i][1] = parts[1];  //Tried this with no joy
                alScores[i][2] = parts[2];

                i = i +1;
            }
            BufferedRdr.close();
            InputSR.close();

        } catch (Exception e) {
            e.printStackTrace();

        }

    }

Thanks,

Airfix

Upvotes: 1

Views: 645

Answers (1)

waynchi
waynchi

Reputation: 144

addAll(...) adds the each element inside an Array into your ArrayList. So by using addAll you're adding Strings into your ArrayList rather than adding a String Array.

To fix this just change alScores.addAll(parts); to alScores.add(parts);

Upvotes: 1

Related Questions