简体   繁体   English

未选中投射警告:将对象强制转换为通用

[英]Unchecked Cast warning: cast Object to Generic

I'm trying to implement a DoublyLinkedList with genenerics. 我正在尝试使用genenerics实现DoublyLinkedList。 According to Java Docs , the argument of remove() method must be an Object. 根据Java Docs ,remove()方法的参数必须是Object。

If I try to cast Object o to T data, I will get the warning: Unchecked Cast: 'Java.lang.Object' to 'T'. 如果我尝试将Object o转换为T数据,我将收到警告: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")" 为了避免这种情况,我必须通过“@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. 我的理解是每个T都是一个对象,但不是每个对象都是T.这就是它显示警告的原因。

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? 但是,当我使用我的DoublyLinkedList类时,我100%确定Object参数是T,有没有办法避免警告或@suppresswarning是唯一的选择?

If my assumption is not correct, what is the correct way to cast an Object to a T? 如果我的假设不正确,将对象强制转换为T的正确方法是什么? Thank you. 谢谢。

The only way to avoid the @SuppressWarning would be to have a field holding the element's class: 避免@SuppressWarning的唯一方法是拥有一个包含元素类的字段:

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. 正如Silvio和Andreas在评论中提到的那样。

No need to cast Object to T, instead, we just need to use .equals() for comparison. 不需要将Object转换为T,相反,我们只需要使用.equals()进行比较。

My initial implementation is to use == operator to compare the object. 我最初的实现是使用==运算符来比较对象。 This is wrong because == is used to compare the reference not the content. 这是错误的,因为==用于比较引用而不是内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM