Dylan Kelemen Dylan Kelemen - 11 months ago 102
Java Question

How to copy only certain elements of one Array to another in Java

I am struggling to create an array with the correct size according to my parameters I have set up. Long story short this program is dealing with a set number of elements in the first array. Those elements are as follows

int [] myWeights = {258, 58, 209, 91, 79, 182, 172, 27, 7, 29, 128, 198};

Now those elements are in ounces. I get the program to run everything correctly, now my professor wants us to separate the ones that are over 8 pounds into a new array. Those elements in the new array in this case are 258, 209, 182, 172, and 198. The problem is that the program, at the beginning, can create a randomly sized array with varying sized elements between the numbers 1-320. Is there a way to have some sort of loop instantiate the proper amount of "boxes" needed. Or am I just supposed to instantiate some arbitrary number and hope that is what I will need? My current code for this is

public static int [] overGivenPounds(int x, int [] array){
int pounds = 0;
int arrayLength = 0;
int arrayOverEightPounds[];
int k = 0;
for(int i = 0; i < array.length; i++){
pounds = array[i] / 16;

if(x < pounds){
arrayOverEightPounds[k] = array[i];

return arrayOverEightPounds;

If any of this seems unclear please ask, there is no need to be rude. I am very new to Java.

Answer Source

Are you allowed to use other classes? If so, you could just use an ArrayList and then use

//int arrayOverEightPounds[];
List<Integer> listOverEightPounds = new ArrayList<>();


    //arrayOverEightPounds[k] = array[i];


return listOverEightPounds.toArray(new Integer[0]);

to return an array of the proper size. In this case you can get rid of k. ArrayList uses an array internally but will resize it automatically if it needs more space so you don't have to do that micro-management. The toArray method on ArrayList will return a new array of the proper size if the array that's passed in is not big enough. A common thing you see is to just pass in an array of size 0 into toArray which means the returned value will always be the correctly sized array.