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
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.
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.
Yes. For example like this:
public class MyWorker<T> {
public void processData(T t){ }
public void processData(List<T> t) {}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With