首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >了解java返回语句中的类强制转换异常

了解java返回语句中的类强制转换异常
EN

Stack Overflow用户
提问于 2012-05-23 20:41:13
回答 2查看 270关注 0票数 1

我已经在这些页面上读到了许多关于类类型转换异常的其他问题,我想确保我的问题本质上是相同的(即与在运行时与编译时相比不知道类的绑定类型有关)。

这是我的测试类..。

代码语言:javascript
运行
复制
public class testCastReturn{
    public test(){

       HashSet<String> StringHash; //a simple hash set

       HashMap(<String, ComplexObject> ObjectInfo; //the String value is the name of the complexObject, and complexObject has multiple members (in this instance it is a java model for a database field so it has info pertaining to Key, size etc)

       //create a ComplexObject here
       addToObjectInfo(aComplexObject); // add it into the HashMap

       //repeat above a number of times....
       //now collect the 'names' of those objects
       StringHash = getObjectKeys();
    }

    public void addToObjectInfo(complexObject c){
        //put a complex object into the HashMap

        ObjectInfo.put(c.getNameID, c); //create a set of key value pairs where the name of the object is the key to get the actual object
    }

    public HashSet<String> getObjectKeys(){
       //retrieve the keys only
       return HashSet<String> this.ObjectInfo.keySet(); //fails with classCastException
       //this however works
       HashSet<String> temp = new HashSet<String>(this.ObjectInfo.keySet());
       return temp;   
    }  
 }//end class

如果我的理解是正确的,这就是为什么我可以用这两种形式编译我的代码,但我只能在显式创建临时位置来保存键集的地方运行代码,因为在运行时,JVM不能保证ComplexObject中键的绑定类型。请记住,这是人为设计的版本,所以可能过度简化了它,在我的实际代码中,我使用了一个“构建器”,然后将信息传递给“最终”的类,然后这些类中的一堆被保存在具有ComplexObjects的HashMap的第三个对象中。

如果您需要任何进一步的信息,请询问(如果您愿意,我甚至可以发送我的库的副本)。

大卫

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-05-23 20:43:34

keySet()返回Set,而不是HashSet。所以return this.ObjectInfo.keySet();应该这样做。

经验法则:总是通过它们的接口而不是它们的类来引用集合(和一般的对象)。因此,比起ArrayListHashSet,更喜欢ListSet。只有在实例化对象或需要特定于具体实现的某些功能时,才使用具体类型。

票数 4
EN

Stack Overflow用户

发布于 2012-05-23 20:46:41

代码语言:javascript
运行
复制
public Set<String> getObjectKeys(){
   return this.ObjectInfo.keySet();
}

这对你有用吗?

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

https://stackoverflow.com/questions/10720117

复制
相关文章

相似问题

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