Hi I need a solution how to create a generic method....
If it is an Integer ArrayList - it adds a random int variable into it and when it is a Double - it adds a random double...
So how to check whether ArrayList<T> is an instanceof Integer or Double and then how to add next random int/double into it...
Slawomir Wieczorek wrote:Hi I need a solution how to create a generic method....
If it is an Integer ArrayList - it adds a random int variable into it and when it is a Double - it adds a random double...
Why would you need to do that?
So how to check whether ArrayList<T> is an instanceof Integer or Double and then how to add next random int/double into it...
You can't. At run-time they are both just ArrayList objects.
Of course there's probably some way to implement your actual requirement, but not the one you asked about here.
Paul Clapham wrote:
Why would you need to do that?
There is no need for that, just a training purpose Let me be more precise ..
Suppose I have a class that stores objects of type Integer or Double (depending which one you choose) in the ArrayList:
So when instantiate such a class:
I will get an object that has an ArrayList<Integer> with 10 random numbers.....
Does it make any sense or rather there's something wrong with me....
Those if (clazz == Foo.class) tests look very unlike object-oriented programming to me. It suggests you need to goback and reconsider your original design.