Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we pass a Single Object as well as as List of Objects in the same Generic PlaceHolders

Tags:

java

generics

My question is pretty simple, can we pass a Single Java Object as well as List of Java Object in the same Generic Placeholders in a method.

example: processData(T t)/processData(List<T> t)

is it possible to clubbed this into one method & one generic place holder which can hold both a single Generic object or List of Generic objects in Java

like image 717
Asif Billa Avatar asked Mar 24 '17 22:03

Asif Billa


People also ask

Can you pass an object to a method?

We can pass the data to the methods in form of arguments and an object is an instance of a class that is created dynamically. The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method.

How do you handle a list of objects in Java?

Since List is an interface, objects cannot be created of the type list. We always need a class that implements this List in order to create an object. And also, after the introduction of Generics in Java 1.5, it is possible to restrict the type of object that can be stored in the List.


2 Answers

Yes. For example like this:

public class MyWorker<T> {
  public void processData(T t){ }
  public void processData(List<T> t) {}
}
like image 77
freedev Avatar answered Oct 21 '22 15:10

freedev


If I understand the question correctly you want a single method that could deal with either a single element or list of certain element type or type-parameter T without overloading.

The closest you can get is to overload and if you want to share the code you could make the single element method delegate into the List method by packing the single element into a singleton list:

class X<T> {
   public void processData(T t) { processData(Collections.singletonList(T)); }
   public void processData(List<T> ts) { ... }; 
} 

However typically you want to customize the code in the single element method to make it run faster in that special case.

If you renounce to List and you are happy to work with arrays instead then you could use a vararg however under the hood you are always passing an array to the method:

class X<T> {
   public void processData(T ... ts) {
       for (T t : ts) { ... };
   } 
} 
...
T x, y, z;
T[] xxx;
...
// the following are all valid calls to processData:
processData(x);
processData(x, y, z);
processData(xxx);
like image 22
Valentin Ruano Avatar answered Oct 21 '22 14:10

Valentin Ruano