I have a linked list of classes which contain 3 strings and a double. I want to collect the total value of each double in the list. For example
LinkedList<Person> L = new LinkedList<Person>();
Person p1 = new Person("Fee","Foo","Bar", 1.2);
Person p2 = new Person("Fi","Fi","Fo", 2.5);
L.add(p1);
L.add(p2);
I would want to find and add up 1.2, and 2.5. I'm assuming I should use ListIterator, but how do I tell it to add each found double value to the total?
You have couple of options to iterate over it
A) Using iterators as asked
Person person = new Person();
ListIterator<Person> listIterator = L.listIterator();
while (listIterator.hasNext()) {
person = listIterator.next();
double value = person.getDoubleAttribute();
}
B) Use a for-each
loop as suggested in other answer:
for(Person person : L){
double value = person.getDoubleAttribute();
}
PS: is highly discouraged to start Java
variables or attributes by UPPERCASE