0

so I have the following bit of code:

while((line = reader.readLine()) != null) {
    String[] row = line.split(",");
    this.table.add(row);  

Where this.table was initiated using:

ArrayList table = new ArrayList();

Then when I tried to get the length a row in table like so:

for(int i=0; i<table.size(); ++i){
    for(int j=0; j<table.get(i).length; ++j) {
        //some code    
        }

It (underlines get(i).length; and gives me an error saying that it cannot find symbol. symbol: length location: class Object.

What's wrong? Does string.split() not return an array? If it does, why can I not use any of the array class methods / variables?

Thank you!

4 Answers 4

2

An ArrayList is not a List of Arrays, it's a list backed by an array.

But you can make it a List of arrays by using generics.

List<String[]> table = new ArrayList<String[]>();

Then your code should work.

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

1 Comment

Thank you. Do I need to import anything to use List? Because it tells me it cannot find symbol?
0

You should use the java generics

List<String[]> table = new ArrayList<String[]>();

Then you would get String[] instances with the get(i) calls. Also note using the List interface to declare the table variable. Wheever possible, use the superinterface that suits your needs, and not the implementation class.

Also, starting from Java 1.5, you can use the much more intuitive for syntax (of course, this assumes that you use the generics recommended before):

for(String[] processedRow : table){
    for(String processedField : processedRow) {
        //some code    
    }
}

1 Comment

Yes, thank you. I tried doing that for loop and it would give me that error so I figured I was implementing the loop wrong. But apparently not :)
0

You need to type your list:

List<String[]> table = new ArrayList<String[]>();

then the java compiler will know the String[] are stored in your list.

Comments

0
ArrayList table = new ArrayList();
//  change with:
ArrayList<String[]> table = new ArrayList();

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.