📜 ⬆️ ⬇️

Incompatibility between the String.split method in Java 8 and Java 7

This is a note about the problem I encountered in the process of transferring a project from Java 7 to Java 8. It happened about six months ago, but I decided to write now, because I suddenly remembered about it (the problem).

So, right off the bat.

Here is the result of the code execution:
package test; import java.util.Arrays; public class Main { public static void main(String[] args) { System.out.println("result: " + Arrays.toString("0000".split(""))); } } 

under Java 8:
 result: [0, 0, 0, 0] 

and Java 7:
 result: [, 0, 0, 0, 0] 


As you can see, the string is split differently, and because of this problem, I caught an ArrayIndexOutOfBoundsException .
It was unpleasant, but I was able to survive, gathered all the will into a fist and decided to figure out what the problem was.
Here is what the official documentation writes:
An empty backing line Produces such a zero leading substring.

Those. Now in a situation where a string is broken by an empty character, a null empty element is not generated.
This behavior is more logical than the old one, but compatibility failure was a surprise for me. In any case, nothing can be done, so I wish you to be careful and catch as few problems as possible :).
')
PS Already later, I found a discussion of this problem on stackoverflow.com.
PPS As the Borz user correctly pointed out, this was a bug . Apparently, it is necessary to read the changelogs better.

Source: https://habr.com/ru/post/241784/


All Articles