byrnesj1
byrnesj1

Reputation: 311

Integer type not working as expected (Java)

I'm writing one of my first programs dealing with generics and standard OOP principles in Java, however I am running into a bit of a problem when dealing with the Integer type.

I noticed that Integers are expected to have a method named compareTo(Integer anotherInteger) in order to compare them as you would ints.

However, when I tried to implement this method in my program I ran into a problem.

error cannot find symbol symbol: method compareTo(Integer) location: variable x of type Integer where Integer is a type-variable: Integer extends Object declared in BinarySearchTree

Essentially, I have x.comporeTo(y) where x & y are of type Integer, but the compareTo method is not found for variable of type Integer (x). Not sure how to solve this, any help would be appreciated.

Thanks

EDIT: I've provided a small example below to highlight my problem. I believe I am shadowing Integer, but I don't know how to get around doing such, or how to fix the problem,

    public class IntgS<Integer>
    {
            Intg<Integer> z = new Intg(3);
            Intg<Integer> y = new Intg(2);
            int w = (z.getX()).compareTo(y.getX());

            public class Intg<Integer>
            {
                    private Integer x;
                    public Intg(Integer x)
                    {
                            this.x = x;
                    }

                    public Integer getX()
                    {
                            return x;
                    }
            }
    }

This gives the same error expressing that Integer type-variable z.getX() does not have a method .compareTo(Integer).

Upvotes: 0

Views: 1658

Answers (1)

Henry
Henry

Reputation: 43798

According to the error message BinarySearchTree has a type parameter called Integer which shadows the standard type java.lang.Integer.

Just remove the type parameter in both classes, i.e.

class IntgS { ... }

Upvotes: 6

Related Questions