How to write Generics Methods and Varargs

1. Introduction

This is third article in Java Generics. In previous articles I discussed about Introduction to Java Generics and cast guarantee provided in Generics. In this article we will see how to write Generic Methods and Varargs.

2. Content

In this article we will see what generic method and varargs is and how to use them.

3. Generic Methods

Let us write a generic method that will accept the array of any type and return the list for that type.

public static <T> List<T> toList(T[] arr) {
 
    List<T> list = new ArrayList<T>();
 
    for (T t : arr) {
        list.add(t);
    }
 
    return list;
 
}

T means type of the any object type.

<T> means a type parameter. It is passed as the method argument and appears in return type too.

You can call this method by using different types.

String[] str = { "Monday", "Tuesday", "Wednesday", "Thursday" };
List<String> list = toList(str);
 
Integer[] ints = { 1, 2, 3, 4 };
List<Integer> list = toList(ints);

4. Varargs

Varargs or variable arguments is a parameter in which you can add arbitrary number of arguments or an array as parameters. Now if you see the parameter for the method toList(T[] arr) it is an array of type T. We can also pass varargs for generic types as follows:

public static <T> List<T> toList(T... arr) {
 
    List<T> list = new ArrayList<T>();
 
    for (T t : arr) {
        list.add(t);
    }
 
    return list;
 
}

See the method parameter toList(T… arr). We can call this method like this

List<Integer> list = toList(1, 2);
 
List<Integer> list = toList(new Integer[] {1, 2, 3});
 
List<String> list = toList("Monday", "Tuesday");

It must be used only as last parameter to any method. At runtime, the varargs are filled in array and then passed to method.

5. Conclusion

In this article we saw what generic method and varargs is. It is better to write generic code if the operation remains same but the type changes.

Leave a Reply

Your email address will not be published. Required fields are marked *