-1

I have a long String and I want to parse it using array of strings like this:

String data = ... very long String delimited by spaces...
String[] parse = data.split(" ");

But I get the following error:

java.lang.ArrayIndexOutOfBoundsException: 4617

Is it possible, that maximum length of String array is 4617 ?

Kick Buttowski
  • 6,709
  • 13
  • 37
  • 58
gaffcz
  • 3,469
  • 14
  • 68
  • 108

3 Answers3

4

The maximum length of an string array in Java is Integer.MAX_VALUE - 5. (Checked with my 64-bit OS with this initialization: String[] myStringArray = new String[Integer.MAX_VALUE-5];. Integer.MAX_VALUE-4 or bigger numbers gives me java.lang.OutOfMemoryError error. The limit can be different for you, since it is machine and OS dependent).

Even if you go beyond that, you will see java.lang.OutOfMemoryError, not java.lang.ArrayIndexOutOfBoundsException.

The problem is definitely with other part of your code.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Tarek
  • 771
  • 7
  • 18
1

use enchance for loop to iterate over parse..Somewhere else in your code you had used wrong index for parse

for(String s:parse){
 System.out.println(s);
}
AsSiDe
  • 1,826
  • 2
  • 15
  • 24
0

No.. There is no max length for the size of an Array. Although you might run into an OutOfMemoryError.

public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("");
    for(int i=0;i<10000000000l;i++){
        sb.append(i).append(" ");
    }
    System.out.println(sb.toString().split("\\s").length);
}

The above code might give OutOfMemoryError on some machines (it did on mine. tried it with jdk 6)

 public static void main(String[] args) {
    StringBuilder sb = new StringBuilder("");
    for(int i=0;i<10000;i++){
        sb.append(i).append(" ");
    }
    System.out.println(sb.toString().split("\\s").length);
}

The above code works fine and prints 1000

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • 1
    The size of an array can't exceed `Integer.MAX_VALUE`, since the language specifies the size of an array as `int` type. The actual limit can be lower, though. – nhahtdh Oct 30 '14 at 08:04
  • @nhahtdh - Where have they mentioned it? – TheLostMind Oct 30 '14 at 08:34
  • [JLS 8.0 - Section 15.10.1](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.10.1) `Each dimension expression undergoes unary numeric promotion (§5.6.1). The promoted type must be int, or a compile-time error occurs.` The length of an array can only be `int` type. – nhahtdh Oct 30 '14 at 08:44