0

I was working with an implementation of the toArray() in ArrayList and came across a scenario which looks like it's an issue (after checking the behaviour from the apidocs). When we copy an arraylist to an array of smaller size, and then print out the contents of the array, it shows null value for all the entries. I was expecting 1. An exception stating that the destination array cannot accommodate all the elements of the source array, or 2. the array to copy only upto the max index it can from the AL.

Following is the code:

import java.util.ArrayList;


public class TestCollections {

  public static void main(String a[]){
    ArrayList<String> arrl = new ArrayList<String>();
    arrl.add("First");
    arrl.add("Second");
    arrl.add("Third");
    arrl.add("Random");
    System.out.println("Actual ArrayList:"+arrl);
    String[] strArrActual = new String[arrl.size()];
    String[] strArrSmaller = new String[arrl.size()-1];
    arrl.toArray(strArrActual);
    arrl.toArray(strArrSmaller);
    System.out.println("Content of actual sized array:");
    for(String str:strArrActual){
        System.out.println(str);
    }
    System.out.println("-----");
    System.out.println("Content of smaller sized array:");
    System.out.println(strArrSmaller.length);
    for(String str:strArrSmaller){
      System.out.println(str);
  }
}
}

Following is the output:

Actual ArrayList:[First, Second, Third, Random]
Content of actual sized array:
First
Second
Third
Random
-----
Content of smaller sized array:
3
null
null
null

Where am I going wrong?

  • The array you are providing is of smaller size right. now how does the collection know which of the elements you want. it can't just give you the first ones. – yaxe Feb 15 '18 at 10:42
  • True. I absolutely second that.Which is why I was expecting it to throw an exception in the first place. What use is it anyway to return nulls? – Anirban Lahiri Feb 16 '18 at 14:37
  • @Anibran Lahiri if you declare an array of n size and there are no elements assigned to any index then they have to be null. – yaxe Feb 17 '18 at 11:20
  • Once again, I know and absolutely understand that. All that I'm trying to point out is why doesn't the function throw up an error stating that the destination is smaller and give out the clear message instead of returning one with nulls, thereby meaning nothing of any value to the user. I just plain think it's a shortcoming of the api, that's all. – Anirban Lahiri Feb 22 '18 at 09:23

0 Answers0