print iterator or stringtokenizer objects to console for checking values
how to print StringTokenizer or Iterator objects to console window using System.out.println() command?
eg: StringTokenizer st = new StringTokenizer(arraylist, delimiter);
system.out.println(st);
when i directly put it in system.out statement like above it prints java.util.StringTokenizer@1224b1
that is java.util.StringTokenizer@somenumber
similar is the case for iterator java.util.AbstractList$Itr@5ceafc
any idea how to print the exact values?
thanks
The [url=http://java.sun.com/j2se/1.5.0/docs/api/java/util/StringTokenizer.html]Javadoc[/url] explains how to get the elements out of the StringTokenizer. Note that for 1.4 and 1.5 of the JDK it also indicates that you should be using split() instead.
To print out the values you'll have iterate the StringTokenizer. For Iterators you need to do the same.
I know you do this:
StringTokenizer st = new StringTokenizer(somevar, "~");
System.out.println(st);
// Output number of tokens in the line
int numberOfTokens = st.countTokens();
System.out.println("Number of tokens = " + numberOfTokens + "\n");
// Output tokens
for (int counter=0; counter < numberOfTokens; counter++) {
System.out.println(st.nextToken());
}
///end
BUt Cant "st" be printed out directly?
> BUt Cant "st" be printed out directly?
Yes, but it won't give you what you want. It will give you the message from your first post - the class name and address of the object.
The StringTokenizer does not have all of the items it may split apart inside of it. It moves to the next token when nextToken() is called. The reason is that you can change the delimiter every time you call - there is a nextToken() that also takes a String.
An Iterator has the same issue. It may have access to all the elements for which it iterates over but it may not, depending on what it is iterating over.
The countTokens() method assumes that the delimiter will not change. It has to be a pretty expensive call as it has to basically run nextToken() internally until it reaches the end.