Convert int to object in Java

I have a problem: I work in an eclipse environment

Sometimes the computer does not give the following conversion:

int a ... 
Object ans = (int) a;

But only this conversion:

int a ...
Object ans = (Integer) a;

I understand why you can convert from object to integer, but why is the original variable - sometimes you can, sometimes you can't convert?

thank you

I attach code that the compiler does not allow me to convert between int variables and objects:

/** @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);
    }

Solution

Before Java 1.5, you couldn't even do this:

int a;
...
Object x = (Integer) a;

The compiler complains that a is a primitive data type and cannot be cast to an object

Since Java 1.5, Java has introduced the concept of automatic boxing Therefore, the following can be:

int a;
...
Object x = (Integer) a;

Because the compiler knows how to automatically convert from the original int to the boxed type integer; From integer to object, it is not a problem

But what you have to do is:

int a;
...
Object x = (int) a;

It basically tells the compiler to avoid boxing You explicitly tell the compiler to leave a as int and put a reference to the int into the object The compiler is not designed to handle this situation

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>