-2

Here i have create a delete method that will search through the Object array and remove the selected object.

public class DogList {
    private int numItems;
    private DogItem[] dogListArray;
    private int position;
    private String name;

    DogList () {
        numItems=0;
        position = 0;
        dogListArray = new DogItem[20]; 
    }

    DogList(String name) {
        this.name = name; 
    }

    public void deleteItem(DogList gi) {
        int i = 0; 
        while( (i < numItems) && (gi != dogListArray[i]) ) {
            i++; 
        }

        if(i == numItems) {
            // Throw exception if there is not matching Item
            throw new NoSuchElementException("That item does not exists"); 
        }
        int pos = i;
        while(pos < numItems -1 ) {
            dogListArray[pos] = dogListArray[pos + 1]; 
            pos++; 
        }
        numItems --; 
    }

I cant wrap my head around why in the first while loop the (gi != dogListArray[i]) is throwing an error:"Incompatible operand types DogList and DogItem"

Any help would be wonderful. The code is pretty long so if you want to see any part i will edit and show what is needed.

Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28
whisk
  • 713
  • 1
  • 10
  • 34
  • Shouldn't it be `gi[i] != dogListArray[i]` ? – Checkmate Sep 25 '16 at 19:12
  • 3
    Looks like your array `dogListArray` contains objects of `DogItem` class. As you are trying to compare it with `DogList`, it returns an error. – Darshan Mehta Sep 25 '16 at 19:12
  • 1
    It'd be helpful if you share the full implementation of class. – Darshan Mehta Sep 25 '16 at 19:14
  • 2
    You should also probably be using an `equals` method to compare objects. If you use `==` or `!=` you'll be comparing references. See http://stackoverflow.com/q/13387742/1288 for details. – Bill the Lizard Sep 25 '16 at 19:14
  • Changing the DogList to DogItem fixed the error @Darshan Mehta. When you say using the equals method @Bill the Lizard, where are you implying that i use it? Im guessing replacing the fist while with somthing like this. `while(!= gi.equal(dogListArray[i]))` ?? – whisk Sep 25 '16 at 19:27

1 Answers1

2

I am assuming that dogListArray is a DogItem[], making dogListArray[i] a DogItem. I assume that gi is meant to be a DogItem as well rather than a DogList?

On a separate but still relevant note, you should use the equals method, rather than == or !=, to compare objects. See here an explanation of this aspect.

Community
  • 1
  • 1
Joe C
  • 15,324
  • 8
  • 38
  • 50