Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through ArrayList <Object<String>>

I'm having some trouble iterating through ArrayList. I have a class named Row which extends ArrayList<String>. I have another class named Table which extends ArrayList<Row>.

I am trying to iterate through the Table class to convert the ArrayList of Rows to a two-dimensional array of Strings.

Here is my code for the Table class:

public class Table extends ArrayList<Row>
{
public Row[] appArray; //Array of single applicant details
public String tableArray[][]; //Array of every applicant
private ArrayList<Row> ar;
private Row r;

public Table()
{
}

public void addApplicant(Row app)
{
    add(app);
    displayable();
}

public void convertToArray()
{
    int x = size();
    appArray=toArray(new Row[x]);
}

public void displayable()
{
int i,j;
for (Row r: ar)
   i=0;
    for(String s: r){
        j=0;
        tableArray[i][j]=s;
        j++;
    }

}}

and here is the Row class:

public class Row extends ArrayList<String>
{
public Row(String appNumber, String name, String date, String fileLoc, String country, Table table)
{
    addDetails(appNumber,name,date,fileLoc,country);
    table.addApplicant(this);
}

public void addDetails(String appNumber, String name, String date, String fileLoc, String country)
{
    add(appNumber);
    add(name);
    add(date);
    add(fileLoc);
    add(country);
}}

The method i am having trouble with is displayable() in the Table class. It tells me i may not have been initialized However if I initialize it in the second for each loop it will only iterate through the first element in my Table ArrayList?

Thanks in advance for any pointers.

like image 581
Hoggie1790 Avatar asked Jul 24 '26 21:07

Hoggie1790


2 Answers

You just missed block in for (Row r: ar) loop.

Also, as Fortega noted, you never increment i in your code, and I suppose that you zero your counters in wrong place.

So, instead of:

for (Row r: ar)
   i=0;
   for(String s: r){
     j=0;
     tableArray[i][j]=s;
     j++;
   }

You should write something like:

i=0;
for (Row r: ar) {
  j=0;
  for(String s: r){
    tableArray[i][j]=s;
    j++;
  }
  i++;
}

Or better to narrow down visibility area of counters and join declarations with initializations:

// Remove previous declarations

int i=0;
for (Row r: ar) {
  int j=0;
  for(String s: r){
    tableArray[i][j]=s;
    j++;
  }
  i++;
}
like image 197
alno Avatar answered Jul 26 '26 10:07

alno


The displayable method has two errors:

  • the first for-loop does not have {}
  • i is not incremented (i++; missing)

code:

public void displayable()
{
  int i,j;
  for (Row r: ar){
    i=0;
    for(String s: r){
        j=0;
        tableArray[i][j]=s;
        j++;
    }
    i++;
  }
}
like image 31
Fortega Avatar answered Jul 26 '26 10:07

Fortega



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!