【发布时间】:2013-12-02 23:57:50
【问题描述】:
下面我有一个包含两个 int 变量的类,我从中创建了许多对象,这些对象存储在链接列表中。现在我想遍历每个对象并将类中的它们的字段与其他 int 值进行比较。换句话说,我想遍历对象的字段而不是对象本身。有什么帮助吗?
import java.util.*;
import java.io.*;
public class Obj
{
int n;
int c;
public Obj (int nn)
{
n = nn;
c = 0;
}
public static void main(String argv[]) throws IOException
{
LinkedList list = new LinkedList();
int i = 7;
Obj element = new Obj(i);
// I may add further objects..
list.add(element);
// then I want to iterate through the linked list of objects and get each object
// and compare its n or c field values with something else
// It should sth like the below which I found in the web but I don;t get how it works
for(Obj elementf : list)
{
// Process each object inside of object here.
}
}
【问题讨论】:
-
您可以使用反射并遍历
elementf.getClass().getFields(),但这几乎肯定不是您想要做的。
标签: java