Java creating instance of ArrayList from other class

Kaspazza :

The situation looks like this:

First class:

class Something {
    List<Object> names;
    public Something(){
       this.names = new ArrayList<Object>();    
    }
}

Second class I tried do something like that and it is not working:

class Main {
    public static void main(String[] args){
        Something names = new Something();
        ...
        for(Object name: names){
           ...
        }
    }
}

And it says that I can't iterate through "names" why? What am I doing wrong?

Tim Biegeleisen :

You probably intend to iterate over the list inside your Something class:

public static void main(String[] args){
    Something something = new Something();
    // then assign something.names to something
    ...
    for (Object name: something.getNames()) {
        // do something
    }
}

So, you probably want to expose a getter and setter for the names list in your class:

class Something {
    List<Object> names;

    public Something() {
        this.names = new ArrayList<Object>();    
    }

    public List<Object> getNames() {
        return names;
    }

    public void setNames(List<Object> names) {
        this.names = names;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=116568&siteId=1