1

I am writing a program that has to read information from file and put them into ArrayList, I think my code is right but Eclipse is saying :The method add(int, String[]) in the type ArrayList<String[]> is not applicable for the arguments (int, String) about account.add(0, x[0]); in my code.

My code:

public static void main(String args[]) {

    ArrayList<String[]> account = new ArrayList<>();
    String line = "";
    try {
        FileReader fr=new FileReader("information.txt");

        Scanner information = new Scanner(fr);
        while (information.hasNext()) {

            // find next line
            line = information.next();

            String x[]=line.split("-");
            account.add(0, x[0]);
            account.add(0, x[1]);
            account.add(0, x[2]);
        }
    }
}
2
  • Do you want each element in the list to be the data for one line of your file, or do you want each line to be transformed into three elements? Commented Jun 15, 2018 at 12:00
  • 1
    You have a try block without a catch (or a finally block or a resource initialisation). Commented Jun 15, 2018 at 12:02

2 Answers 2

4

This is the signature of the method you're using :

public void add(int index, E element) { ... }

You have ArrayList<String[]>, so the method expects an array of Strings as a second param. And what you provide is just a String (element from the array).

Try this:

String x[]=line.split("-");
account.add(0, x); // because x is actually an array

Or you can use it like that:

account.add(x);

If you still need to put elements from the array into your list like you do here:

account.add(0, x[0]);
account.add(0, x[1]);
account.add(0, x[2]);

try to change ArrayList<String[]> to ArrayList<String>.

And just a comment that has nothing to do with your question :) This is a better practice:

// use interface List in the left part :)
List<String[]> account = new ArrayList<>();

Happy hacking :)

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

Comments

0

You should to just write account.add(x[0]); For example:

ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("smth");

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.