user2121038
user2121038

Reputation: 153

Moving informations from file into ArrayList

When I try to move data from textfile into arraylist I get error on line data.add(row); (no suitable method found) how can I solve it ? Is using arraylist good idea if I want to use it to populate java jtable(swing) ?

 public ArrayList<String> getinformationforthetable() {
    Scanner s = null;
    ArrayList<String> data = new ArrayList<String>();
    try {
        s = new Scanner(new File("info.txt"));
        while (s.hasNextLine()) {
        String line = s.nextLine();
        if (line.startsWith("")) {
            String[] atoms = line.split("[#]");
            ArrayList<String> row = new ArrayList<String>();
            row.add(atoms[0]);
            row.add(atoms[1]);
                    row.add(atoms[2]);
                    row.add(atoms[3]);
                    row.add(atoms[4]);
                    row.add(atoms[5]);
            data.add(row);

        }
        }
    }
    catch(IOException e) {
        e.printStackTrace();    
    }
    finally {
        if (s != null) {
        s.close();
        }
    }
    return data;
    }
}

Upvotes: 0

Views: 83

Answers (3)

newuser
newuser

Reputation: 8466

You are trying to add the List values as String. It wont allow to add. List having the default method as addAll() to add the list values into the mainList

data.add(row);

instead of

data.addAll(row);

Upvotes: 4

MadProgrammer
MadProgrammer

Reputation: 347194

data is decalred as expecting String values, but your are adding an ArrayList of Strings to it...

ArrayList<String> data = new ArrayList<String>();
//...
ArrayList<String> row = new ArrayList<String>();
data.add(row);

Depending on what you want to achieve and based on the example code, you should do something more like...

ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();

If you want to be able to add the row ArrayList to the data ArrayList...

Upvotes: 3

Sanjeev
Sanjeev

Reputation: 9946

This error is due to the fact that your data array list is an Array list of strings

  ArrayList<String> data = new ArrayList<String>();

and you are trying to add another array list to it. you should change it to

  List<List<String>> data = new ArrayList<List<String>>();

Hope this helps.

Upvotes: 5

Related Questions