Reputation: 1885
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]
Upvotes: 1
Views: 115
Reputation: 115
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;
}
Upvotes: 3
Reputation: 48404
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.
Upvotes: 5