简体   繁体   中英

iterate through the fields of each object of a linked list

Below I have got a class with two int variables from which I have created a number of objects which I have stored in the linked list. Now I want to loop through each object and compare THEIR FIELDS from the class with other int values. In other words I want to loop through the fields of the objects and not the objects themselves. Any help?

 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.
 }

}

First, use LinkedList<Obj> and not just a raw LinkedList ; the compiler should be complaining about the existing code.

As for "iterating over the fields", that doesn't really make sense. Just iterate over the Obj objects in the list and do something inside that for loop with elementf.n and elementf.c .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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