Search code examples
javaarrayscomparable

Is there a way to instantiate a comparable array, just establishing its length


I need to "extract" if you will, one particular row of a multi array of comparables. I know the index of the row, I just need a copy of it. I tried just doing something like:

masterList is the multiarray that I need to extract from.

Comparable[] extracted = masterList[i];

This however only sets extracted to the address and not the actual contents.

Is there an easy way to do this?

If not can I create an empty Comparable[] of the same length as the masterList[i] row and loop through to add to it? Please note that my program doesn't start off knowing the length of the row it needs so I can't hard code it into the program.

Updated code:

    Comparable[][] comparable = Arrays.copyOf(masterList, masterList[i].length);

When I ran this I did get an array of the length I need but it was all addresses, not values. So I ran a loop to add the values

for(int i = 0; i<comparable.length; ++i){
        comparable[i] = queries[masterIndex];
    }

this however still returns a list of addresses.


Solution

  • Have you tried System.arraycopy?

    Comparable extracted[] = new Comparable[masterList[i].length]
    System.arraycopy(masterList[i],0, extracted, 0, extracted.length);
    

    This should make a shallow copy of the elements at masterList[i][j=0 to length-1] in extracted.

    Please note that both of the solutions described here will throw a NullPointerException if master list[i] happens to be null. Be sure to check for that to avoid a nasty runtime surprise.

    System.arraycopy is handy if you want to copy a part of the array. Here is a good discussion on both the approaches.

    Hope this helps!