The Java documentation doesn't seem to mention anything about deprecation for StringTokenizer
, yet I keep hearing about how it was deprecated long ago. Was it deprecated because it had bugs/errors, or is String.split()
simply better to use overall?
I have some code that uses StringTokenizer
and I am wondering if I should seriously be concerned about refactoring it to use String.split()
, or whether the deprecation is purely a matter of convenience and my code is safe.
StringTokenizer is not deprecated
It is little different function and output ...
For example, if you have
"aaa.aa.aa"
and want to split it into the parts"aaa"
,"aa"
and"a"
, you can just write:If you just use:
It returns an empty array, because it matches regular expressions where
.
is a spacial character. So you have to escape it:So basically .. split enable you to use regex ... it can be very usefull
But StringTokenizer parse text by tokens ... and token can be even special character
I don't think so that the reason of that is String.split method, because split is slow way to parse the string - it compiles a pattern inside.
StringTokenizer just can be replaced with a more functional classes like java.util.Scanner or your can use pattern matcher to get the groups by regexp.
Personally I feel StringTokenizer was deprecated because it was simply an complex way of doing something pretty simple. StringTokenizer as the name implies only applied to Strings so why not just made it a method in String. Further StringTokenizer didn't support RegularExpression does not support regular expression which became extremely common in the late 90's and early '00's hence rendering it practically useless.
From the javadoc for StringTokenizer:
If you look at
String.split()
and compare it toStringTokenizer
, the relevant difference is thatString.split()
uses a regular expression, whereasStringTokenizer
just uses verbatim split characters. So if I wanted to tokenize a string with more complex logic than single characters (e.g. split on\r\n
), I can't useStringTokenizer
but I can useString.split()
.If it is not marked as deprecated, it is not going away.
StringTokenizer is not deprecated in fact StringTokenizer is 4X faster than String.split() and in competitive programming it is used by many developers.
Source :- Faster Input for Java