4

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.

2

4 Answers 4

10

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

newValues[] = Arrays.copyOfRange(values, 2, 6);
Sign up to request clarification or add additional context in comments.

2 Comments

While this is working fine for single-dimensional Arrays, this does not answer the multidimensional part of the question.
I agree. But, each multidimensional array can be converted to 1D array and transformed with this function.
2

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

1 Comment

wat abt multi-dimenstion array?
2

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

1 Comment

This is EXACTLY what I'm looking for. I would mark this right, but I'm looking for something more "built in". Do you know if there is something equivalent to Arrays.copyOfRange() for multi-dimensional arrays?
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.