Link to home
Start Free TrialLog in
Avatar of shampouya
shampouya

asked on

Is my definition of a generic method in Java ok?

Here's my basic definition of a generic method. Is it acceptable?

Generic Method - a method in which type parameters appear within angled brackets, right before the return type. The code below is a generic method that uses an enhanced for loop to add array elements to a collection one by one. The third line of the code would not have compiled if the <T> at the beginning of the method signature was not there. That <T> made it possible for the array and the collection in the method parameter to be typed the same generic way, so that this method would be compatible with any object type.

static <T> void fromArrayToCollection(T[ ] a, Collection<T> c) {
     for (T o : a) {
        c.add(o); // adding an array element of type T
     }
}
Avatar of for_yan
for_yan
Flag of United States of America image

Yes, this seems fine to me
if it compiles then it is fine
And it does compile fro me
Although my IDE suggest to replcae it withh Collection.addAll method, but this does not matter; once it compiles it measn it is correct
Avatar of shampouya
shampouya

ASKER

And the <T> after the word static is what turned this method into a generic method, right?
Yes, without that "T" in fromt of static compiler would not understdn what means T inside the mthod and in parameters
So this code compiles fine together with your method definition:

  
        Collection<String> cc = null;
        String [] cmcm = null;
        
            fromArrayToCollection(cmcm, cc);
        

Open in new window

Oh I know it compiles, correctly, I took it from the Oracle website. I was just wondering if my english was correct when I defined a generic method. And I was wondering if the <T> before the return type is what can turn a regular method into a generic method.

Aslo this compiles:

        Collection<Object> cc = null;
        String [] cmcm = null;

            fromArrayToCollection(cmcm, cc);

Open in new window


but this does not:


Collection<String> cc = null;
        Object [] cmcm = null;

            fromArrayToCollection(cmcm, cc);

Open in new window


This is in compliance with your previous
statements about covariance of arrays and collections
I'm confused and I'm not sure why you are telling me what compiles.That wasn't my question....
I just liked that your talks about covariance of arrays vs collections in previous question are nicely illustrated by this example
 
ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks