Cast int int Object on java

advertisements

I have a question: I work in environment of Eclipse.

Sometimes the computer does not give to the following casting:

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

But only this conversion:

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

I understand why you can do the casting between Object to Integer, but why primitive variable - there are times when you can, and there are times you can not do a casting?

Thank you

I am attaching the code which the compiler not let me make casting between int variable to 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);
    }


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

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

The compiler would complain that a is of a primitive data type, and therefore cannot be cast to an object.

Starting with Java 1.5, Java introduced the concept of automatic boxing. So, the following became OK:

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

Because the compiler knows how to convert from a primitive int to the boxed type Integer automatically; and from Integer to an Object it's, well, not a problem.

However, what you're trying to do:

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

Is basically telling the compiler to avoid boxing. You explicitly tell the compiler to leave a as an int, and put a reference to that int into an Object. The compiler isn't designed to deal with such a case.