Jared
Jared

Reputation: 33

Casting a generic variable java

I'm currently unsure as to how you can do mathematical operations on a generic variable without casting them to an integer. Doesn't casting a generic variable defeat the object of generics in java?

Super class:

public interface someClass {

public <E> boolean test(E object);

}

Problem class:

public class isOdd implements someClass {

public <E> boolean test(E object) {

    if ( (object % 2) == 0) {

        return false;

    }
    else {

        return true;

    }

    }

}

I'm unsure as to how to add either upper bounds or a wildcard to make sure the object is an Integer. Is there a way of changing the super class generic method so that it can be used by other types like String and such?

Thanks.

Upvotes: 0

Views: 385

Answers (3)

Andreas
Andreas

Reputation: 5113

Number might be the supertype you're looking for

interface hasParity {
    public boolean isOdd();
}

public class NumberWithParity<T extends Number> implements hasParity {
    private T value;

    public NumberWithParity(T value) {
        this.value = value;
    }

    public T getValue() {
        return value;
    }

    public void setValue(T value) {
        this.value = value;
    }

    @Override
    public boolean isOdd() {
        return getValue().longValue() % 2 == 1;
    }
}

Upvotes: 0

BarrySW19
BarrySW19

Reputation: 3819

The best way is to make the interface take any type and the implementation use a specific type:

public interface SomeClass<E> {
    public boolean test(E arg);
}

public class IsOdd implements SomeClass<Integer> {
    @Override
    public boolean test(Integer arg) {
        return arg % 2 == 1;
    }
}

You could then instantiate it thus:

SomeClass<Integer> realTestClass = new IsOdd();
boolean result = realTestClass.test(1);

Upvotes: 0

AtlasMeh-ed
AtlasMeh-ed

Reputation: 477

It would certainly be wrong to pass in anything to this code. I think you are focused on the subclasses of java.lang.number like Integer and Double. Instead why don't you make your code accept Number objects.

public boolean isOdd(Number number) {
    if ( (number.longValue() % 2) == 0) {
       return false;
    }
    else {
       return true;
    }

}

Upvotes: 1

Related Questions