我只是一个初学者,我想要一个好的灵魂来帮助我;)我得到了这个方法,并在线路上:
( (HashSet<String>) pos[targetPos]).add(word);它给了我一个例外
(Unchecked cast from Object to HashSet<String>)我试图更具体地将Objectpos更改为Stringpos,但随后在下面的代码行上显示错误: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];发布于 2013-04-12 00:10:52
“未检查的类型转换”消息是一个警告。编译器警告您,它不能确保在运行时从Object到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"
...
}另外,考虑使用Set<String>的List而不是数组:
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"
...
}发布于 2013-04-12 00:11:07
pos[]被定义为Object数组。当您稍后将其强制转换为HashSet<String>时,Java并不知道您可以做到这一点。这就是未检查的强制转换--编译器警告您可能正在做一些不安全的事情。
您可以通过将pos的类型更改为HashSet<String>[]来消除警告。
https://stackoverflow.com/questions/15953666
复制相似问题