4

I have a stringTokenizer set up and I want to have a copy of it for another process. Is there a way of doing this? My code:

StringTokenizer itr = new StringTokenizer(theBigString);
itr.nextToken();
// My goal is to get a new StringTokenizer after the first token
//StringTokenizer itrCopy = new StringTokenizer(itr.toString());

Is there any way to get this done?

suman
  • 195
  • 13
  • 1
    As @SergeyTachenov said, using StringTokenizer is kind of a bad idea. What are you trying to achieve? Maybe you can do it by passing that other process a substring of the original string, like this: `theBigString.substring(0, theBigString.indexOf("tokenSeparator"))` and then instantiate a new StringTokenizer for that new string in the other process. – walen Oct 18 '16 at 08:40
  • @walen Thanks mate. I know how to use it with splits and substrings, just wanted to know if there is a way of doing it with stringTokenizer. The docs didn't have anything – suman Oct 18 '16 at 14:09

1 Answers1

2

This may not answer your question exactly, but, quoting StringTokenizer docs,

StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.

Unfortunately, this doesn't mention exactly why it's discouraged. And the reason is, you have to load the entire string into memory anyway to use StringTokenizer, and that implies you're not terribly memory-constrained, so why not use split? Pretty much the only reason to use StringTokenizer today is when you set returnDelims to true (if different delimiters mean different things to you) because you can't do that with split.

If you still have some reason to use StringTokenizer, then you have a serious problem here. StringTokenizer is not Serializable, and you can't inherit from it and make it Serializable because it doesn't have the void constructor. Which means your only way is to use reflection, possibly with some 3rd party serialization libraries, maybe serialize it to XML/JSON. But the absence of default constructor may limit your choices here as well. When deserializing, you'll have to construct the tokenizer with some dummy string first, and then set its fields via reflection.

Sergei Tachenov
  • 24,345
  • 8
  • 57
  • 73
  • Thanks mate for the answer. I was just trying to understand if there was a way of doing it. I ended up using split method. – suman Oct 18 '16 at 14:11