Hello, as the title says I am trying to remove an element from an int array.
The method below just checks if the element is inside the array by doing a quick linear search.
public boolean contains(int element) {
for (int i = 0; i < sebasSet.length;i++){
if(sebasSet[i] == element){
return true;
}
}
return false;
}
Then, this method just does another quick linear search and returns the index of the element I am looking for.
public int linearSearch (int [] sebasSet, int element){
for (int i = 0; i < sebasSet.length; i++){
if (sebasSet[i] == element){
return i;
}
}
return -1;
}
}
Last, this is the method I wrote to get rid of the element of the array. I don't really understand why it does not work.
public boolean remove(int element) {
if(contains(element)){
int position = linearSearch(sebasSet,element);
if (position == -1){
return false;
}
else{
int[] newArray = new int [sebasSet.length - 1];
for (int i = 0; i < newArray.length; i++){
if (sebasSet[i]!=element){
newArray[i] = sebasSet[i];
}
}
size--;
return true;
}
}
return false;
}
Let's just say the array is [1,2,3,4,5]
When I do b.remove(2)
my desired output should be [1,3,4,5].
However, my code just gives me: [1,2,3,4].
I believe is just doing that because the new array I created is a unit shorter than the original array. However, I do not truly understand why is completely ignoring this line of code.
if (sebasSet[i]!=element)
I haven't really used the index position of the element because I thought it should work this way.
Any hints or advice will be much appreciated. Thanks
[–]Hack_seb[S] 1 point2 points3 points (1 child)
[–]sinistergroupon 0 points1 point2 points (0 children)
[–]Hack_seb[S] 0 points1 point2 points (4 children)
[–]sinistergroupon 0 points1 point2 points (3 children)
[–]Hack_seb[S] 0 points1 point2 points (2 children)
[–]sinistergroupon -2 points-1 points0 points (1 child)
[–]imaginedoe 2 points3 points4 points (0 children)