【问题标题】:iterate through the fields of each object of a linked list遍历链表的每个对象的字段
【发布时间】: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


【解决方案1】:

首先,使用LinkedList<Obj> 而不仅仅是原始LinkedList;编译器应该抱怨现有的代码。

至于“遍历字段”,这并没有什么意义。只需遍历列表中的Obj 对象,然后在for 循环中使用elementf.nelementf.c 执行一些操作。

【讨论】:

  • 哦,是的。当我把 LinkedList 它工作。我不明白为什么以及如何......对不起,我只是 Java 的新手。你能否解释/给我一个链接/为什么一般的 LinkedList 不起作用?谢谢
猜你喜欢
  • 2023-02-13
  • 2015-11-19
  • 2020-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-06
  • 2016-05-20
  • 1970-01-01
相关资源
最近更新 更多