Search code examples
javastringbuffer

Buffer for String like IntBuffer


Is there a class in Java ( 8+ ) that has similar functionalities as IntBuffer or other classes inheriting fom java.nio.Buffer but for String items? Implementing my own version would be simple for my need is very simple (only mark a position in the middle of the array), but I'd like to know if there is already a class for that.

Thanks.

Update: I'm sorry if the problem wasn't understood clearly, but what I need is to mark a position in the array of strings, i. e. to save the last used index so I know when all the array has been used. Like:

String[] array = new String(){"str1", "str2", ...};
int mark = 0;
String get() throws Exception{
   // Throw exception if out of bound
   return array[mark++];
}
boolean hasNext(){
   return mark<array.length();
}

which is what IntBuffer does with int items, I think.

Thanks.


Solution

  • As Slaw pointed out, Iterator does what you want:

    String[] array = {"str1", "str2", "str3"};
    Iterator<String> iterator = Arrays.asList(array).iterator();
    
    while (iterator.hasNext()) {
        String element = iterator.next();
        System.out.println(element);
    }
    

    If you want to keep track of the current index in the list/array, or if you want to be able to navigate both forwards and backwards, you can use a ListIterator:

    String[] array = {"str1", "str2", "str3"};
    Iterator<String> iterator = Arrays.asList(array).listIterator();
    
    while (iterator.hasNext()) {
        String element = iterator.next();
        System.out.println(element);
    }
    

    (This code is identical to the first code block, except for calling listIterator() instead of iterator().)

    The Iterator, ListIterator, and Arrays classes are all in the java.util package.