Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new array with contents from old array while keeping the old array static

Tags:

java

arrays

Say I have an array of integers,

int[] array = new int[7];
for(int i = 0; i < 7; i++)
{
array[i] = i;
}

Now i want to get only the first four numbers in that array, and turn put that into another array.

So I really want something like...

newArray = array[0-3].

I know that syntax is wrong, but I'm just giving the general idea of what I'm trying to do, is anything like that possible? Or do i have to create a loop and add it manually into the newArray?

like image 430
ObjectiveC-InLearning Avatar asked Nov 19 '11 10:11

ObjectiveC-InLearning


People also ask

How do you create an array from an existing array in PHP?

The array_unshift() function adds new elements to the array. The new array values will be inserted at the beginning of the array. You can insert one value or as many as you like. Numeric keys will start at 0 and increase by 1 every time a new element is added.


2 Answers

int[] newArray = Arrays.copyOf(array,4);
like image 100
Adithya Surampudi Avatar answered Nov 15 '22 18:11

Adithya Surampudi


Method 1

int[] newArr = new int[4];
System.arraycopy(array, 0, newArr, 0, 4);

The method takes five arguments:

  1. src: The source array.
  2. srcPosition: The position in the source from where you wish to begin copying.
  3. des: The destination array.
  4. desPosition: The position in the destination array to where the copy should start.
  5. length: The number of elements to be copied.

This method throws a NullPointerException if either of src or des are null. It also throws an ArrayStoreException in the following cases:

  • If the src is not an array.
  • If the des is not an array.
  • If src and des are arrays of different data types.

Method 2

Utilize

Arrays.copyOf(array,4) to copy the first 4 elements, truncating the rest.

of

Arrays.copyOfRange(array,1,5) to copy elements 1-4 if you need the middle of an array.

like image 26
Jonathan Schneider Avatar answered Nov 15 '22 18:11

Jonathan Schneider