iterator - How do I modify each element in an Iterable<T> in Java? -
this question has answer here:
- can 1 each loop in java in reverse order? 11 answers
i've searched far can , i'm struggling find answer question.. have iterable object , want modify each item in (i not want add it) new value. i've tried
for (t e : list) { e = a.get(index); system.out.println(e); index--; } to modify didn't work, because foreach loop. can show me i'm doing wrong code? (the idea i'm trying reverse iterable's item order.)
public class linkedlist<t> { iterable<t> list; public linkedlist() {} //create empty list public linkedlist(iterable<t> iterable) { list = iterable; } @suppresswarnings("unchecked") public iterable<t> reverse() { integer size = size(); list<t> = new arraylist<t>(); integer index = size - 1; (t e : list) { a.add(e); } iterator iterator = list.iterator(); while (iterator.hasnext()) { t element = (t)iterator.next(); element = a.get(index); system.out.println(element); index--; } return list; } }
you need understand loop construct:
for (t e : list) this assigns variable e, copy of reference object in list.
you tried assign new value e:
e = a.get(index); but achieves overwriting copy of reference. list list continues use reference has used.
your end goal return iterable travels in reverse direction? have few options here.
- keep underlying list unchanged, make custom iterator provide reverse view on it. iterator can supply
iterable<t>, return. - shuffle around contents of underlying list, such list itself in reverse order (you can use
collections.reverse(list)this). natural iteration order resemble "reverse" iteration of original list. - same above, instead of mutating existing list: create reversed copy of list.
one thing you're doing make hard this:
iterable<t> list; public linkedlist(iterable<t> iterable) { list = iterable; } does need accept specific iterable? instead accept list (giving ability lookup elements @ index)? if has iterable, may not have store iterable. insert contents arraylist, , variable list list.
Comments
Post a Comment