首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java中的"Unchecked cast“警告说明

Java中的"Unchecked cast“警告说明
EN

Stack Overflow用户
提问于 2013-04-12 00:07:25
回答 2查看 527关注 0票数 0

我只是一个初学者,我想要一个好的灵魂来帮助我;)我得到了这个方法,并在线路上:

代码语言:javascript
复制
( (HashSet<String>) pos[targetPos]).add(word);

它给了我一个例外

代码语言:javascript
复制
    (Unchecked cast from Object to HashSet<String>)

我试图更具体地将Objectpos更改为Stringpos,但随后在下面的代码行上显示错误:pos[targetPos] = new HashSet<String>();

代码语言:javascript
复制
Type mismatch: cannot convert from HashSet<String> to String

方法如下:

代码语言:javascript
复制
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
    }

}

根是

代码语言:javascript
复制
 Object[] root = new Object[28];
EN

回答 2

Stack Overflow用户

发布于 2013-04-12 00:10:52

“未检查的类型转换”消息是一个警告。编译器警告您,它不能确保在运行时从ObjectHashSet<String>的显式转换可以安全地发生,这意味着如果您的Object类型的数组包含HashSet<String>以外的内容,当JVM试图将该对象转换为HashSet<String>类型时,您可能会在运行时获得一个ClassCastException。本质上,编译器预先警告你,你正在做一些潜在的不安全的事情,这可能会在以后成为问题的根源。

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

您的方法应该如下所示:

代码语言:javascript
复制
public void add(String word, Set<String>[] root){

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

另外,考虑使用Set<String>List而不是数组:

代码语言:javascript
复制
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"
    ...
}
票数 3
EN

Stack Overflow用户

发布于 2013-04-12 00:11:07

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

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15953666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档