Reputation: 163
I defined a linked list of Candidate
objects. I need to store the initial next element for every element (since I would be changing the order later, and require the initial order).
public class Candidate {
//data members
private String prefrence;
private Candidate next;
public void setNext(Candidate c){ next=c; }
//rest of the class body
}
In a separate class I need to create a list of candidates (candidateList
) where I have to initialize it,
while(input) {
Candidate c = new Candidate(field[0], field[1], field[2], ...);
candidateList.add(c);
}
Now, I need to store the next element of list in c.next
. I also require to iterate over the entire list and change the preference of candidate in list. However, I don't know how to access the elements of the list.
Basically, I know the c++ equivalent where pointer to Candidate
(ptr), ptr->datamember=abc;
would do the job. But I am new to Java and can't get the hang of pointer mechanism here. I intend something like this:
ListIterator<Candidate> itr = candidateList.listIterator();
while(itr.hasNext()) {
Candidate c = itr.next(); //I am supposing this creates a copy while i need a reference
func(c.pref);
c.pref = abc;
c.next = def;
}
In short, I need to change the value of elements in a linked list and not change the element itself.
Upvotes: 1
Views: 3643
Reputation: 393841
itr.next()
of ListIterator
of LinkedList
doesn't create a copy.
public E next() {
checkForComodification();
if (nextIndex == size)
throw new NoSuchElementException();
lastReturned = next;
next = next.next;
nextIndex++;
return lastReturned.element;
}
It returns a reference to a Candidate
object stored in the list. Therefore you can update the returned Candidate
, which would update the Candidate
object in the list.
Upvotes: 1