Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is String.split() in Java guaranteed to return an ordered array?

Tags:

java

string

split

I'm writing an application where I'm receiving a message that is a sequence of tag1=value1|tag2=value2|tag3=value3 etc. I want to split it around the | delimiter.

Having read the Javadoc there is nothing to say that the String.split(String regex) method is guaranteed to maintain the original order of the message. I've played about and it seems ok, but I'd rather not commit to this approach if I'm going to get caught out later.

So, does anybody know if there are any situations where the order of array elements returned by split() can be altered from the original String? Or can anyone point out any documentation that says the order is guaranteed to be maintained?

(Apologies if this is a dupe, but I can't find a similar question on the site.)

like image 714
neilgmacy Avatar asked May 22 '12 13:05

neilgmacy


People also ask

Does string split return an array?

The split() method splits a string into an array of substrings. The split() method returns the new array.

Does string split preserve order?

Yes, . split() always preserves the order of the characters in the string.

What does split method return in Java?

The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings.

What happens when you split a string in Java?

The string split() method breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.


2 Answers

The javadoc says:

The substrings in the array are in the order in which they occur in this string.

EDIT: the above is for the two-argument split(String regex, int limit) version, but the single-argument version

works as if by invoking the two-argument split method with the given expression and a limit argument of zero.

like image 52
Graham Borland Avatar answered Sep 29 '22 11:09

Graham Borland


I'm seeing The substrings in the array are in the order in which they occur in this string. in http://docs.oracle.com/javase/7/docs/api/java/lang/String.html...

like image 30
Alexander Pavlov Avatar answered Sep 29 '22 10:09

Alexander Pavlov