J Meister J Meister - 1 year ago 77
Java Question

Length of Array returning wrong number?

I'm trying to print the size of an array using the

method. However, at the end it is always returning 1 and not 4.

Here is my code:

int size = 4;
ArrayList<String> testArr = new ArrayList<String>();
String [] test = null;

for (int i = 0; i < size; i++) {
test = testArr.toArray(new String[0]);

System.out.println(test.length); // returns 1

Answer Source

No problem

You code does indeed return 4 as you expected, not 1 as you stated.

I took your code as-is, adding an extra println and modifying the other println.

int size = 4;
ArrayList<String> testArr = new ArrayList<String> ();
String[] test = null;

for ( int i = 0 ; i < size ; i ++ ) {
    testArr.add ( "test" );
    test = testArr.toArray ( new String[ 0 ] );
    System.out.println ( "i: " + i + " | test: " + Arrays.toString ( test ) );

System.out.println ( "test.length: " + test.length );

i: 0 | test: [test]

i: 1 | test: [test, test]

i: 2 | test: [test, test, test]

i: 3 | test: [test, test, test, test]

test.length: 4

Be sure to read the class doc to understand the behavior of this command:

ArrayList::toArray( array )

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

If the list fits in the specified array with room to spare (i.e., the array has more elements than the list), the element in the array immediately following the end of the collection is set to null. (This is useful in determining the length of the list only if the caller knows that the list does not contain any null elements.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download