How to remove all duplicates of ints in an array java -
i needed create method remove occurrences of integers in array. when integers removed, whole list needs shifted down empty spaces filled next integers. currently, method removes 1 occurrence of given integer.
public void removeall(int val) { (int n = 0; n < list.length; n++) { //goes through each integer if (list[n] == val) { //checks if value user enters (int j = n; j < list.length - 1; j++) { list[j] = list[j + 1]; } list[elements - 1] = 0; //elements amount of elements in array elements--; } } }
you close:
i recommend not using list.length
rather elements
throughout. otherwise, algorithm break when val = 0
, list contains 0
.
public void removeall(int val){ for(int n = 0; n <elements;n++){ // < -- change list.length elements if(list[n] == val){ (int j = n; j<elements-1;j++){ // < -- change list.length elements list[j]=list[j+1]; } list[elements-1]=0; elements--; n--; // <-- add line not skip on 'n + 1'th term } } }
the problem iterating on collection skipping next term after removal.
for example, val = 2
, list = 1 2 2 3 4 4
:
the algorithm identifies , removes value:
1 2 2 3 4 4 ^
after array looks , next position checked n
has been incremented @ next item in collection. it's not hard see problematic when items match removal criteria next each other (adjacent) in example.
1 2 3 4 4 0 ^
in order compensate event - need decrement n
n--;
when encounter item removed collection. keeps n
looking @ same index in array until index no longer occupied to-be-removed item (aka items match removal criteria adjacent).
update
what happens if count of array not used upper limit throughout , val = 0
array contains @ least 1 0
?
i'll keep theme , illustrate issue example.
let val = 0
, list = 1 2 0 3 4 4
. usual, algorithm identifies , removes value.
1 2 0 3 4 4 ^
now array looks this:
1 2 3 4 4 0 ^
however, since algorithm still iterating on collection until index equal list.length
still valued @ 6 (it's not being decremented elements
). algorithm end @ faux item @ index 5 of collection. trouble begins.
1 2 3 4 4 0 ^
the index never move there going adjacent 0
we're adding them end of collection signify unused indexes! collection this:
0 0 0 0 0 0 ^
in following iteration - indexoutofboundsexception
thrown java list[-1] = 0
occur.
hope helps!
Comments
Post a Comment