简体   繁体   中英

Using boolean remove(Object o) in linked list

This is the remove() method

public boolean removeId(Object d) {
    boolean removed=false;
    curr=fNode; 

    if(curr==null)
      throw new RuntimeException("cannot delete");

    else if(curr.data==d) {       

        fNode=fNode.next;
        curr=fNode;
        removed=true;
      }

    else  
      curr=curr.next;


    count--;
    return removed;
}

The class

public class Hospital {

    private int id;
    private String name;
    private double price;
    private String treatType;
    private String date;

    public Hospital()  {
        id=0;
        name="NA";
        price=0;
        treatType="NA";
        date="NA";    
    }

    public Hospital(int a,String b,double c,String d,String e) {
        id=a;
        name=b;
        price=c;
        treatType=d;
        date=e;
    }

    public void setHospital(int a,String b,double c,String d,String e) {
        id=a;
        name=b;
        price=c;
        treatType=d;
        date=e;
    }

    public int getId(){ return id; }
    public String getName(){ return name; }
    public double getPrice(){ return price; }
    public String getTreatType(){ return treatType; }
    public String getDate(){ return date; }

    public String toString()  {
        return ("Id :"+id+"\nName :"+name+"\nPrice :"+price+"\nTreatment type :"+treatType+"\nDate :"+date);
    }
  }

In main

System.out.println("Enter id you want to remove :");
int remId=in.nextInt();

list.removeId(new Integer(remId));

Why isn't the id in the first node removed? I tried it to remove the first node but it does not remove it. I tried a lot of ways including change the remId to int but it still does not work.

Now, I make some changes to the remove() method by eliminating the 'while' and use 'equal' but it does not make any sense. Then I tried another change and it works Why this code works?

public boolean removeId(Object d)
{
    boolean removed=false;

    curr=fNode;
        if(curr==null)
            throw new RuntimeException("cannot delete");

        else
            {
                    fNode=fNode.next;
                    curr=fNode;
                    removed=true;
            }


            curr=curr.next;

    count--;
    return removed;
}

The reason is that you're comparing Integer objects with == . Use the equals() method instead.

When you compare objects in Java using == , you compare them for identity , not for equality . The == will yield true if and only if both of its operands are the very same identical object. It will yield false in any other case, which includes the case in which the two operands are equal but not same .

Your code is using Integer , which is a class and therefore you can create two Integer objects which are equal but not same:

public static void equalsVsSameIntegerDemo() {
    final Integer i1 = new Integer(1);
    final Integer i2 = new Integer(1);
    System.out.println(i1.equals(i2)); // true
    System.out.println(i1 == i2); // false
}

Alternatively, if you know it's Integer and it cannot be null , you could use int instead of Integer . But this only works if you're using int in the remove -method. If you use int in the caller, and call remove(Object) , the int would get converted into an Integer . If your ids are to be quite generic, you want to go for equals() instead of == .

In your code, you have if (curr.data==d)

But are you sure that new Integer(remId) == theObjectInsertedInTheList ?

I do not think so, and here lies your problem.

More info: Object Equality

您应该将节点的数据与equals而不是== ,后者仅检查两者是否为同一实例:

if(curr.data.equals(d))

You are using object identity to test for equality:

if (curr.data == d)

which is only true if the two operands are the same object, which they aren't. Change that line to:

if (curr.data.equals(d))

which compares the two objects' values (at least for the Integer class).

Note that your algorithm will still fail even after you use the right comparison because your fNode and curr are not moving together.

When deleting, you are removing a given link from a chain - let's say the chain is made of the following links: A --> B --> C --> D . Deleting C would mean removing the link that points from B --> C and and replacing it with a link that points from B --> D . So you go from A --> B --> C --> D to A --> B --> D

The algorithm, in pseudo code would be.

 1. start at the beginning of the list with the first node (Head of the list).
 2. check if it is the one you want to delete.
 3. if not, go to the next node and repeat step 2 
 4. if so, make the next node of the previous node the next node of this node
 5. remove the reference from this node to the next node

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