Getting list values using Iterator Java -
i'm trying use list iterator walk linked list , operations / checks on next node depending on integer value stored there, i'm getting errors in code. think i'm not understanding iterator.next() returning (some e object, don't know how access value want it) editor wants me casting explained below. gets rid of errors, don't know if safe way handle problem or if has behavior i'm looking for. please explain why getting errors , if there way handle this.
linkedlist<integer>[] hash = new linkedlist[list.size()]; hash = remo.createhash(hash, list.size()); listiterator iterator = list.listiterator(0); // use value of integer stored @ next node hash // , add same value linked list @ bucket int = 0; while(iterator.hasnext()){ hash[iterator.next()].add(iterator.next()); i++; } // reset iterator beginning of list iterator = list.listiterator(0); // if hash bucket corresponding value @ node has more // 1 item in list, remove node list. while(iterator.hasnext()){ if(hash[iterator.next()].size()>1){ iterator.remove(iterator.next()); } }
createhash initializes each linked list in array , remo instance of class.
the editor wants me cast iterator.next() int hash[iterator.next()] , wants me cast in .add(iterator.next()).
example: hash[(int)iterator.next()] hash[(int)iterator.next()].add((integer)iterator.next());
linkedlist<integer>[] hash = new linkedlist[list.size()];
this line problematic due http://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createarrays
you cannot create arrays of parameterized types. example, following code not compile: list<integer>[] arrayoflists = new list<integer>[2]; // compile-time error because: object[] stringlists = new list<string>[]; // compiler error, pretend it's allowed stringlists[0] = new arraylist<string>(); // ok stringlists[1] = new arraylist<integer>(); // arraystoreexception should thrown, // runtime can't detect it. if arrays of parameterized lists allowed, previous code fail throw desired arraystoreexception.
as such, creating array of lists aren't using generics (as cannot create arrays of parameterized types), , such, stores objects (it doesn't know type you're planning store). should use arraylist
instead of array
fix problem, so:
list<list<integer>> listoflists = new arraylist<list<integer>>(list.size()); //example usage listoflists.add(new linkedlist<integer>()); for(list<integer> currlist : listoflists) { ... }
Comments
Post a Comment