简体   繁体   中英

compacting an array in java by removing certain objects

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?

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.

I think you want equals() rather than == unless testing for null. You are using an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM