简体   繁体   中英

using java iterators like c++ iterators

    Vector <String> songList;
    Iterator<String> begin= songList.iterator();
    Iterator<String> end= songList.iterator();

Say I have a vector list of songs just like the list in itunes. How would I set the begin iterator to the beginning and the end iterator to the ending without iterating through the whole list? Additionally how would I move the end iterator in the reverse direction until I meet a certain criteria? The best I could find online was the hasnext/next functions but those are forward only? I'm new to java and tried searching for the answer but I don't know what key terms to search for. In essence what I am trying to do is narrow down a list of songs from a thousand to a few by keeping a pointer to the beginning and ending of the songs that start with a pattern. So if I am searching for "the" I want to return a lower bound iterator and upper bound iterator for all the songs that start with "the". Then I want to keep adjusting these iterators as the user goes from typing "the" to "ther" to "there"... etc. I am aware that java doesn't use pointers like c++ uses. I am just trying to do what I said in the fastest way possible. Please help!

From the description of what you want to do, you don't really want to use a list at all: what you want is a TreeSet . You can use the subSet(from,to) method to search for songs that start with a pattern.

Either way, given a list, you can obtain an iterator that points to the last item of the list with:

ListIterator<String> end= songList.iterator(songList.size()-1);

Note that it points to the last item, not to one item past the last. You can iterate backwards using the previous() and hasPrevious() methods defined in the ListIterator interface .

Also, you should use the ArrayList class instead of Vector . As you can read in Vector's documentation,

Unlike the new collection implementations, Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector.

Iterator object is used for iterating for forward direction and only for once. While Listiterator obj is used for iterating forward and backward direction, as well as we can iterate object more than once.

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