aspose file tools*
The moose likes Beginning Java and the fly likes generic method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "generic method" Watch "generic method" New topic
Author

generic method

Slawomir Wieczorek
Greenhorn

Joined: Dec 07, 2011
Posts: 20

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
Bartender

Joined: Oct 14, 2005
Posts: 18669
    
    8

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

Joined: Dec 07, 2011
Posts: 20

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
Bartender

Joined: Oct 14, 2005
Posts: 18669
    
    8

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

Joined: Dec 07, 2011
Posts: 20

Thank you Paul
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: generic method