• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

generic method

 
Slawomir Wieczorek
Greenhorn
Posts: 20
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Paul Clapham
Sheriff
Pie
Posts: 20739
30
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Slawomir Wieczorek
Greenhorn
Posts: 20
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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....
 
Paul Clapham
Sheriff
Pie
Posts: 20739
30
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The usual way for a generic class to know about one of its parameterized types is for the class to ask to be given that type at run-time. Like this:

Then to create one of those things:
 
Slawomir Wieczorek
Greenhorn
Posts: 20
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Paul
 
Campbell Ritchie
Sheriff
Posts: 48382
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic