-1

I have a class StudentArrayList inherit interface SimpleArrayList

the SimpleArrayList have the function: retainAll

 /**
 * Retains only the elements in this list that are contained in the
 * specified student.SimpleArrayList. In other words, removes from this list all of
 * its elements that are not contained in the specified student.SimpleArrayList.
 *
 * @param c
 *            student.SimpleArrayList containing elements to be retained in this
 *            list
 * @return <tt>true</tt> if this list changed as a result of the call
 */
 boolean retainAll(SimpleArrayList<E> c);

I created a function corresponding in StudentArrayList like this:

@Override
public boolean retainAll(SimpleArrayList c) {        
    if (c.size()==0){
        this.clear();
        return true;
    }
    int temp=this.size;
    int count=0;
    boolean check=false;
    for(int i=0;i<this.size;i++){
        for(int j=0;j<c.size();j++){
            if(this.studentList[i].equals(c.get(j))) check=true;
        }
        if(!check) {
            this.remove(i);
            //this.size--;
            check=false;
        }
    } 
    if(temp==this.size) return false;
    return true;

I don't know why my coding get wrong answer. Could anyone please explain for me why?

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35

1 Answers1

0

Try this:

@Override
public boolean retainAll(SimpleArrayList c) {        
    if (c.size()==0){
        this.clear();
        return true;
    }
    int temp=this.size;
    int count=0;
    
    for(int i=0;i<this.size;i++){
        boolean check=false;
        for(int j=0;j<c.size();j++){
            if(this.studentList[i].equals(c.get(j))) check=true;
        }
        if(!check) {
            this.remove(i);
            //this.size--;
            check=false;
        }
    } 
    if(temp==this.size) return false;
    return true;

If not post more code, but it appears your logic is wrong.

Pearl
  • 392
  • 2
  • 12