5

i'm trying copy an array without a specified element. Let's say I have the following arrays:

int[] array = {1,2,3,4,5,6,7,8,9}; int[] array2 = new int[array.length-1]; 

what I want is to copy array to array2 without the element containing the int "6" so it will contain "{1,2,3,4,5,7,8,9}"

I only want to use for loops and this is what I have so far but it doesnt work

int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] array2= new int[array.length - 1]; int remove = 6; for (int i = 0; i < array2.length; i++) { if (array[i] != remove) { array2[i] = array[i]; } else { array2[i] = array[i + 1]; i++; } } for (int i = 0; i < array2.length; i++) { System.out.println(array2[i]); } 

Thanks

3
  • What are tab and tab2? And "but it doesnt work" is not a good replacement for an error message. Commented Oct 5, 2014 at 21:58
  • my bad, tab is array and tab2 is array2 Commented Oct 5, 2014 at 22:02
  • What exactly doesnt work? do you get an error? another result? just plain nothing? Commented Oct 5, 2014 at 22:07

3 Answers 3

7

You can also do it using Java 8's streams and lambda expressions:

int[] array= { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] array2 = Arrays.stream( array ).filter( value -> value != 6 ).toArray(); System.out.println( Arrays.toString( array2 ) ); // Outputs: [0, 1, 2, 3, 4, 5, 7, 8, 9] 
Sign up to request clarification or add additional context in comments.

Comments

5
int j = 0; int count = 0; //Set this variable to the number of times the 'remove' item appears in the list int[] array2 = new int[array.length - count]; int remove = 6; for(int i=0; i < array.length; i++) { if(array[i] != remove) array2[j++] = array[i]; } 

4 Comments

thanks but the last element of array2 is not copied, there a 0 instead of a 9
@BobJ I guess you forgot to change int count = 0; to int count = 1;?
no ive put array.length2 instead of array.length . thanks it works
You may want to use the count since there may be duplicate values in the array which will result in the array having a series of 0's at the end.
0

ArrayUtils.remove(array, 6) from apache.commons.lang might also be suitable

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.