Reputation: 1
For my computer science class we are supposed to take an array of objects {A,C,D,C,C,F,C,G} and sets all elements of a certain object to null. Object is C: {A,null,D,null,null,F,null,G} Then we are supposed to move all the remaining object to the front of the array {A,D,F,G,null,null,null,null}... So far I tried this but I cant find the problem with my method:
public static void compact (Object[] vec, Object item) {
int a=0;
for(int i=0; i < vec.length; i++)
{
if(vec[i]==item)
{
vec[i] = null;
}
else
{
vec[i]=vec[a];
a++;
}
}
for(int b=a; b < vec.length-(a-1); b++)
{
vec[b]=null;
}
}
Help please?
Upvotes: 0
Views: 626
Reputation: 184
I think you want equals() rather than == unless testing for null. You are using an object.
Upvotes: 0
Reputation: 24885
if(vec[i]==item)
Never use ==
for comparing objects, use equals()
(and, when you define a new class, take care in implementing equals()
and hashCode()
in a practical way)
Of course there may be other problems, but since you are not even telling what it is failing I won't care much.
Upvotes: 4