Rob Avery IV
Rob Avery IV

Reputation: 3740

Java - Return an array from array with two given indexes

Let's say I have an array:

int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0};

With two indexes (let's say 2 and 5), I want to be able to return array from indexes 2 to 5 from the variable values given above. The final output should be this:

newValues[] = {3, 4, 5, 6};

Also, how would this procedure be used with multi dimensional arrays?

I would have googled this, but I'm not sure what to google, so I came here.

Upvotes: 4

Views: 6134

Answers (4)

Ritz
Ritz

Reputation: 180

You can use the following :

int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0}; int newValues[] = new int[4]; System.arraycopy(values,1,newValues,0,4)

Here's the complete code :

public class CopyRange {    
  public static void main (String...args){
     int[] values = {1, 2, 3, 4, 5, 6, 7 , 8, 9, 0};
     int newValues[] = new int[4];

     System.arraycopy(values,1,newValues,0,4);

     for (int i =0;i <newValues.length;i++)
        System.out.print(newValues[i] + " ");
     }
}

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

Upvotes: 1

Try the following for 2D arrays:

public int[][] getRange(int[][] src, int x, int y, int x2, int y2) {
    int[][] ret = new int[x2-x+1][y2-y+1];
    for(int i = 0; i <= x2-x; i++)
        for(int j = 0; j <= y2-y; j++)
            ret[i][j] = src[x+i][y+j];
    return ret;
}

For 1D Arrays, Arrays.copyOfRange() should be fine and for more dimensions you can simply add more params and for loops

Upvotes: 2

user987339
user987339

Reputation: 10707

Use java.util Arrays class. Use copyOfRange(int[] original, int from, int to) method:

newValues[] = Arrays.copyOfRange(values, 2, 6);

Upvotes: 10

Christian Tapia
Christian Tapia

Reputation: 34166

Try the following

public static void main(String[] args)
{
    int[] values = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };

    int start = 2, end = 5; // Index
    int[] newValues = new int[end - start + 1]; // Create new array

    for (int i = start; i <= end; i++) {
        newValues[i - start] = values[i]; // Assign values
    }

    // Print newValues
    for (int v : newValues) {
        System.out.print(v + " ");
    }
}

Output:

3 4 5 6

Upvotes: 2

Related Questions