繁体   English   中英

Java中“未检查的强制转换”警告的解释

[英]Explanation of “Unchecked cast” warning in Java

我只是一个初学者,我想要一个好的灵魂来帮助我;)我得到了这种方法,然后就可以了:

( (HashSet<String>) pos[targetPos]).add(word);

它给了我一个例外

    (Unchecked cast from Object to HashSet<String>)

我试图将Object [pos]更改为String [pos]更具体,但随后在此行上给了我一个错误: pos[targetPos] = new HashSet<String>();

Type mismatch: cannot convert from HashSet<String> to String

这是方法:

public void add(String word, Object[] root){

    Object[] pos = root;
    int wordIndex = 0;
    int targetPos;

    if(word.length()>=3){
        for(int i = 1; i <=3; i++){
            targetPos = word.charAt(wordIndex) -'a'; //convert a letter into index eg a==0
            if(i==3){
                if(pos[targetPos]==null){
                    pos[targetPos] = new HashSet<String>();
                }
                ( (HashSet<String>) pos[targetPos]).add(word);
                //System.out.println(Arrays.toString(pos));
                break;

            }//end if outer if
            else{
                if(pos[targetPos]==null){
                    pos[targetPos] = new Object[28];
                }
                wordIndex++;
                pos =  (Object[]) pos[targetPos];
            }
        }//end of for
    }

}

根是

 Object[] root = new Object[28];

“未经检查的演员表”消息是警告。 编译器警告您,无法确定从ObjectHashSet<String>的显式HashSet<String>可以在运行时安全地进行,这意味着,如果您的Object类型的数组包含除HashSet<String>之外的其他内容 ,则可能当JVM尝试将该对象转换为HashSet<String>类型时,将在运行时获取ClassCastException 本质上,编译器会事先警告您,您正在做某些可能不安全的操作,以后可能会引起问题。

简单地使用数组的原始对象不是一个好习惯。 如果要确保该数组仅包含HashSet<String>对象,则可能应该这样键入它(即Set<String>[] ;使用接口而不是该类型的具体实现)因为这样您就可以在需要时切换实现)。 唯一应该进行显式转换的时间是,您可以绝对确定要转换的对象绝对是您要转换到的对象的类型。 例如,如果您有一个实现接口的对象,并且还假设您属于某个类中,那么该类肯定可以使用该接口的特定具体实现。 在这种情况下,可以将其从该接口转换为具体类型。

您的方法应如下所示:

public void add(String word, Set<String>[] root){

    Set<String>[] pos = root; //You probably don't even need this since you have "root"
    ...
}

此外,考虑使用一个ListSet<String>而不是数组:

public void add(String word, List<Set<String>> root){

    List<Set<String>> pos = root; //You probably don't even need this since you have "root"
    ...
}

pos[]被定义为Object数组。 稍后将其转换为HashSet<String> ,Java不知道您可以这样做。 这就是未经检查的强制转换-编译器警告您,您可能正在做某些不安全的事情。

您可以通过将pos的类型更改为HashSet<String>[]来消除警告。

暂无
暂无

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

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