我有一个问题:我在
Eclipse的环境中工作.
有时计算机不会给出以下转换:
int a ... Object ans = (int) a;
但只有这种转换:
int a ... Object ans = (Integer) a;
我明白为什么你可以在Object to Integer之间进行转换,但为什么是原始变量 – 有时你可以,有时候你不能进行转换?
谢谢
我附加编译器不允许我在int变量和object之间进行转换的代码:
/** @return minimum element */ public Object minimum(){ return minimum(this.root); } public Object minimum(BSTNode node){ if (node.left != null) return minimum(node.left); return node.data; } /** @return maximum element */ public Object maximum(){ return maximum(this.root); } public Object maximum(BSTNode node){ if (node.right != null) return maximum(node.right); return node.data; } public Object findNearestSmall(Object elem) { int diff; diff = (int)maximum() - (int)minimum(); if (compare(minimum(),elem) == 0) return elem; else return findNearestSmall(elem,this.root,diff); } public Object findNearestSmall(Object elem,BSTNode node,int mindiff){ if(node == null) return (int)elem - mindiff; int diff = (int)elem - (int)node.data; if(diff > 0 && mindiff > diff) mindiff = diff; /* Case 2 : Look for in left subtree */ if(compare(node.data,elem)>-1) return findNearestSmall(elem,node.left,mindiff); else /* Case 3 : Look for in right subtree */ return findNearestSmall(elem,node.right,mindiff); }
解决方法
在Java 1.5之前,你甚至无法做到这一点:
int a; ... Object x = (Integer) a;
编译器会抱怨a是原始数据类型,因此无法强制转换为对象.
从Java 1.5开始,Java引入了自动装箱的概念.所以,以下变得可以:
int a; ... Object x = (Integer) a;
因为编译器知道如何自动地从原始int转换为盒装类型Integer;从Integer到Object,它不是问题.
但是,你要做的是:
int a; ... Object x = (int) a;
基本上是告诉编译器避免装箱.您明确告诉编译器将a保留为int,并将对该int的引用放入Object中.编译器不是为处理这种情况而设计的.