R71
R71

Reputation: 4523

checks on generic/template type

I am trying to create a generic container (e.g. java code below), which has some restrictions, e.g items bigger than some limit cannot be put in it. Problem is that since T is an unknown type, the comparison function with an integer is reporting an error. How to fix this problem?

Secondly, is there a solution if the code was written in C++?

public class Box<T> {
    private T val;
    private int max;

    public Box (int m, T initval) { max = m; val = initval; }

    public T get() { return val; }
    public void set(T newval) {
        val = newval;
        if(newval.toInt() >= max)    // error on toInt
             System.out.printf("ERR: size too big\n");
        }
}

Upvotes: 0

Views: 85

Answers (3)

Cedric Mamo
Cedric Mamo

Reputation: 1744

Some objects simply don't have the toInt() method. In your case you can only call methods contained in the Object class (from which all classes inherit).

If you are sure what types of objects will be used with it you can type cast it into your desired type and access the toInt() method from that. However since it's a generic container you won't have control over that.

Another way to make sure that there is a toInt() method to execute is to make the generic accept an interface. You can define toInt() inside the interface, and you will be able to use the container with any class that implements that interface.

As I said earlier, the way you're doing it, you can only access the Object class' methods. So, in a nutshell, implementing a truly general purpose container that uses anything other than Object's methods in the way you have described is not possible

Upvotes: 2

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

You should have

interface ToIntable {
  int toInt();
}

and

public class Box<T extends ToIntable> {
...
    if (newval.toInt() >= max) doSomething();
...
}

Upvotes: 3

alex.p
alex.p

Reputation: 2739

Could you use an interface instead of using generics? In this case it would probably just be a marker interface with no methods to denote types that can be used on the container.

Upvotes: 0

Related Questions