This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android 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: 18541
    
    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: 18541
    
    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: 38045
    
  22
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
 
Similar Threads
How to get a random number
ArrayList
creating an object
about random.next int();
The following method generates an OutOfMemoryError, how to overcome that?