Rohit Pandey
Rohit Pandey

Reputation: 2681

How to pass ArrayList of different types to method?

I want to define a method -

public static void summary1(ArrayList<Type> a){
    //some code        
}

I want to have the flexibility of replacing "Type" with any thing (Integer, Double, Long, etc). Is that possible?

Upvotes: 0

Views: 1370

Answers (5)

Bohemian
Bohemian

Reputation: 424993

If you literally mean "anything", and you don't need access to the type within the method:

public static void summary1(List<?> list){
}

If you need access to the type:

public static <T> void summary1(List<T> list){
    // type T is available to code in here
}

All your examples were Number classes, so if you want to restrict it to those:

public static <T extends Number> void summary1(List<T> list){
   // a list of Numbers
}

and if you also need the Comparable behaviour that all Number classes have (but Number alone does not):

public static <T extends Number & Comparable<T>> void summary1(List<T> list){
   // a list of Numbers, and you can compare them
}


Note also that I have changed the type to the abstract type List, instead of the implementation ArrayList - see Liskov substitution principle

Upvotes: 2

Derrick
Derrick

Reputation: 336

I'm not a Java expert, but from what I know, you will need to explicitly create methods for each type you expect to see. For example:

public static void summary1(ArrayList<String> a){
    //some code        
}

public static void summary1(ArrayList<Integer> a){
    //some code        
}

public static void summary1(ArrayList<Double> a){
    //some code        
}

etc...

Then as your method is called, the correct method will be invoked based on the type that is passed to it.

Upvotes: 0

Narendra Pathai
Narendra Pathai

Reputation: 41935

public static <T> void summary1(ArrayList<T> list){
   //now you can pass any list here
}

If you want to use T in some way.

or you can use wildcard operator ? if you don't care what type of List is being passed to summary1

References: - Generics and wildcard

Upvotes: 4

Trein
Trein

Reputation: 3688

You can use <?> notation as

public static void summary1(ArrayList<?> a){
    //some code        
}

Also, if you want to restrict to subtypes of Number, you can add

public static void summary1(ArrayList<? extends Number> a){
    //some code        
}

Upvotes: 3

xp500
xp500

Reputation: 1426

Yes, you have to use the wildcard ?. So ArrayList<?> would mean an ArrayList of anything. By what you wrote, I assume you just want numbers, so you can do something like ArrayList<? extends Number> so that you can only pass ArrayLists of classes that extend Number.

Upvotes: 2

Related Questions