Reputation: 323
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?
Upvotes: 2
Views: 2353
Reputation: 140319
The other answers give fine solutions. But what if you do want to use just something
in the enhanced for loop?
You have to make the class implement Iterable
:
class Something implements Iterable<Object> {
And implement the iterator()
method:
@Override public Iterator<Object> iterator() {
return names.iterator(); // for example.
}
Now you can write:
for (Object object : something) { ... }
and it will be acceptable to the compiler.
But you should only do this if Something
is-a Iterable of Objects, i.e. that it is intrinsically modelling something which should be iterated (e.g. it is "like a List"). Otherwise, if it merely has-a Iterable of Objects, stick to the other proposed solutions.
Upvotes: 2
Reputation: 567
Your Something
class is not a List
. But it contains a List
.
class Something {
List<Object> names;
public List<Object> getNames(){
this.names = new ArrayList<Object>();
}
public void setNames( List<Object> list ){
this.names = list;
}
}
class Main {
public static void main(String[] args){
Something somethingObj= new Something();
List<Object> newNames = new ArrayList<>();
newNames.add( new Object() );
somethingObj.setNames( newNames );
for(Object name: somethingObj.getNames()){
...
}
}
}
Upvotes: 1
Reputation: 521053
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;
}
}
Upvotes: 2
Reputation: 29081
Try not to call your Something
instance names
. names
is a member of the Something
class instance. You are trying to iterate your Something
class, and not names
array inside it.
class Main {
public static void main(String[] args){
Something something = new Something();
...
for(Object name: something.names){
do smth;
}
}
}
Upvotes: 1