I am using generics in java, and I want to know how I can test to see if I have a int or a float? Is there some sort of type-testing? I'm sure there is, I just need someone to help point me in the right direction. Thanks!

Recommended Answers

All 6 Replies

huh?
What are you trying to do?
If you have to worry about the exact type of a genericised argument to a method the decision to use generics at that stage was wrong.

well I have either an int or a float all the calculations are the same except for the constructor, where I need to call either java.util.Random nextInt or nextFloat

The question still makes no sense. You can't generically pass a primitive as a parameter, so you would need separate signature for each anyway, which alleviates the ambiguity.

well then I can pass it as an Integer and a Float

well then I can pass it as an Integer and a Float

Yes, and that is a different story. You repeatedly said you were working with int and float, which are not the same thing.
You can use the "instanceof" operator to check the type of an object variable.

(I think you also mean "abstraction" in your original question - not generics, based on the question. Generics are a type parameterization mechanism introduced in Java 1.5)

If your method implementation can work with both integer and floating point numbers, why handle them differently?
If it can't, why use generics to template away the difference in the method signature?

I assume you pass in an argument of type <E extends Number> ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.