blaa
blaa

Reputation: 811

Iterate over array of objects Java

So, I have a class Model01:

public class Model01 {

private String color;
private String name;
private String bl;

    public String getColor() {
    return color;
}


public void setColor(String color) {
    this.color = color;
}

public String getName() {
    return name;
}


public void setName(String color) {
    this.name = name;
}

public String getBl() {
    return bl;
}


public void setBl(String color) {
    this.bl = bl;
}

At a certain point in my code I want to map some data I receive from the database onto this model class like this:

List<Model01> resultEntries = new ArrayList<Model01>();
for(Object[] i : res){ // res is the result of my query
Model01 m = new Model01();
   m.setColor((String) item[0]);
   m.setName((String) item[1]);
   m.setBl((String) item[2]);
 resultEntries.add(m)
}

Later on in my code I want to iterate over my array of resultEntries, which contains many objects and I want to compare some fields between my objects. I've done it something like this, but it seems that it only iterates over my last object. What am I doing wrong ?

for(Model01 i : resultEntries){
if (i.getName.equals(i.getBl))
...
System.out.println(...);
}

EDIT: I am always instantiating a new Model01 object and these code snippets are actually inside a function that performs some queries to the database and everytime the method is called a new object will be created with new values inside the for.

Upvotes: 1

Views: 5140

Answers (1)

M.Nouman Shahzad
M.Nouman Shahzad

Reputation: 46

In the last step, when you are trying to iterate over your List 'resultEnteries', you are using a 'for each' loop and will have access to only a single object of the list at a time.

You can try using an iterator:

Iterator<Model01> it = resultEnteries.iterator();
Model01 current = it.next();
Model01 next = it.next();

while (it.hasNext()) {
    if (current.name.equals(next.getB1) {
        ...
    }
    current = next;
    next = it.next();
}

Upvotes: 1

Related Questions