简体   繁体   English

遍历对象数组Java

[英]Iterate over array of objects Java

So, I have a class Model01: 因此,我有一个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. 稍后在我的代码中,我想遍历resultEntries数组,其中包含许多对象,并且我想比较对象之间的某些字段。 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. 编辑:我总是实例化一个新的Model01对象,这些代码片段实际上是在对数据库执行一些查询的函数内,并且每次调用该方法时,都会在for中使用新值创建一个新对象。

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. 在最后一步中,当您尝试遍历列表'resultEnteries'时,您将使用'for each'循环,并且一次只能访问列表的单个对象。

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM