3

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.

3 Answers3

3

If not can I create an empty Comparable[] of the same length as the masterList[i] row and loop through to add to it?

No need. You can just do

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

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.

See, you need not to hard code the length as well.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • @Suresh, you answer is more concise than mine. +1! – Prashant Sep 26 '15 at 18:09
  • This seems like it should work, but when I try to print out the new extracted array it is still giving me a list of addresses not values? –  Sep 26 '15 at 18:10
  • Can you please update with your new code ?? Do not modify the current, just paste new code as an update or ask new question :) – Suresh Atta Sep 26 '15 at 18:12
  • @Read_My_Feels991 `Arrays.copyOf(masterList,` should be `Arrays.copyOf(masterList[i],` ? – Suresh Atta Sep 26 '15 at 18:21
2

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!

Community
  • 1
  • 1
Prashant
  • 1,002
  • 13
  • 29
0

You can use clone(), because all arrays are Cloneable:

Comparable[] extracted = masterList[i].clone();

This will create a shallow copy of masterList[i] (if masterList[i] is null, you'll get a NullPointerException).

Roman
  • 6,486
  • 2
  • 23
  • 41