Iterate a String array within an object

Asked

Viewed 58 times

0

I built the following object:

public class TableHelper {

    private String TABLE;
    private String[] COLUMNS;

    public TableHelper (String name, String[] columns){
        this.TABLE   = name;
        this.COLUMNS = columns;
    }

    // GETTERS
    public String name(){
        return TABLE;
    }

    public String[] columns(){
        return COLUMNS;
    }

    // SETTERS
    public void name(String name){
        this.TABLE = name;
    }
    public void columns(String[] columns){
        this.COLUMNS = columns;
    }

}

And I’m the popular one array with a set of objectos equal to the above in the following way:

public static List<TableHelper> tableList = Arrays.asList(
        new TableHelper("menu", new String[]{
                "id         PRIMARY KEY AUTOINCREMENT",
                "position   INTEGER",
                "active     INTEGER"
        }),

        new TableHelper("menu_languages", new String[]{
                "id         PRIMARY KEY AUTOINCREMENT",
                "menu_id    INTEGER",
                "language   TEXT",
                "title      TEXT",
        }),

        new TableHelper("submenu", new String[]{
                "id         PRIMARY KEY AUTOINCREMENT",
                "menu_id    INTEGER",
                "position   INTEGER",
                "active     INTEGER"
        }),

        new TableHelper("submenu_languages", new String[]{
                "id         PRIMARY KEY AUTOINCREMENT",
                "submenu_id INTEGER",
                "language   TEXT",
                "title      TEXT",
        })
);

What I need now is to iterate the field String[] COLUMNS inside each object within the array. I already have this but I know it’s wrong. How can I do what I want using the cycle for:

for (TableHelper tables : Config.tableList){
    for(TableHelper col : tables.columns()){
        Log.e("COLUMN", tables2.toString());
    }
}

1 answer

2


Try this:

for (TableHelper tables : Config.tableList){
    for(String col : tables.columns()){
        Log.e("COLUMN", col);
    }
}

Explanation:

  • The type of return of your method columns is String and not TableHelper. The compiler must have complained about it.
  • In your loop there is no variable tables2. But even if you did, every iteration you’d be logging into the same thing over and over again, and this thing that’s not what you’re iterating on. I mean, it wasn’t what you wanted. What you wanted is the column you’re iterating, which is col.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.