简体   繁体   中英

Java: add element after an element in the LinkedList

I want to add an element after an element in the list if list already contain that element otherwise I want to add this new element to beginning of the list.

Somehow below code is not working.

Any suggestions?

Does this approach correct performance wise?

public class HelloWorld
        {
          public static void main(String[] args) {
          LinkedList<Task> l =new LinkedList<Task>();

            l.add(new Task("a")); 
            l.add(new Task("b"));
            l.add(new Task("c")); 

            int index;

            if((index = l.lastIndexOf(new Task("a"))) != -1){
               l.add(++index, new Task("5"));
            }else{
               l.addFirst(new Task("6"));
            }        
            System.out.println(l);
      }
    }

    class Task{
     String value;

      Task(String v){
        value = v;
      }

      public boolean equals(Task t){
        return t.value.equals(this.value);
      }  

      public String toString(){  
       return this.value; 
      }
    }

Output produces: [6,a,b,c]

Expected output: [a,5,b,c]

You are not overriding Object#equals in your Task class.

You need to parametrize it with Object , otherwise it's an overload.

That in turn doesn't allow your new Task("a") to be equal to new Task("a") , as Object.equals in invoked instead, and the references don't match.

This in turn will cripple your lastIndexOf invocation with unexpected results.

Example

@Override
public boolean equals(Object obj) {
    // TODO your code, i.e. based on the "value" field
}

If you're using an IDE (which I recommend), you will have features allowing to draft equals (and hashCode ) implementations based on your desired properties.

Your equals should look like that.

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    Task task = (Task) o;

    return value != null ? value.equals(task.value) : task.value == null;

}

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