I'm trying to implement a DoublyLinkedList with genenerics. According to Java Docs , the argument of remove() method must be an Object.
If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'.
public boolean remove(Object o) {
T data = (T) o; // warning here
...
}
To avoid this, I have to suppress the warning by "@SuppressWarning("Unchecked")"
@SuppressWarnings("unchecked")
public boolean remove(Object o) {
T data = (T) o;
...
}
My understanding is every T is an Object but not every Object is a T. That's why it shows the warning.
But what if when I use my DoublyLinkedList class, I'm 100% sure the Object argument is a T, is there a way to avoid the warning or @suppresswarning is the only choice here?
If my assumption is not correct, what is the correct way to cast an Object to a T? Thank you.
The only way to avoid the @SuppressWarning
would be to have a field holding the element's class:
public class DoublyLinkedList<T> ... {
...
private final Class<T> elementClass;
...
public DoublyLinkedList(Class<T> elementClass) {
this.clazz = elementClass;
}
...
public boolean remove(Object o) {
T data = elementClass.cast(o);
...
}
...
}
As Silvio and Andreas mentioned in the comments.
No need to cast Object to T, instead, we just need to use .equals() for comparison.
My initial implementation is to use == operator to compare the object. This is wrong because == is used to compare the reference not the content.
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.