Method overload

I was wondering if you can offer anything here.

I would like to have 2 methods:

doSomething(List<Data>) and doSomething(List<Double>) 

Since the parameter type is the same, Java complains

Is there a way to somehow do this overload?

+4
source share
5 answers
 public void doSomething(List list) { if(list.size() > 0) { Object obj = list.get(0); if(obj instanceof Data) { doSomethingData((List<Data>)list); } else if (obj instanceof Double) { doSomethingDouble((List<Double>)list); } } } 
+3
source

Unfortunately not. Since Java implements generics with erasure, these two methods will be compiled to:

 doSomething(List) 

Since you cannot use two methods with the same signature, this will not compile.

The best you can do is:

 doSomethingData(List<Data>) doSomethingDouble(List<Double>) 

or something just as unpleasant.

+7
source

Why not just name them differently:

 doSomethingDouble(List<Double> doubles); doSomethingData(List<Data> data); 
+2
source

Generics are available only to the compiler at compile time. They are not a runtime construct, since the two methods described above are identical, since at runtime both are also equivalent to doSomething (List) .

+1
source

This does not work due to the type of erasure . The only thing you can do is add a dummy type parameter:

 doSomething(List<Data>, Data) doSomething(List<Double>, Double) 

Ugly, but it works.

Alternatively, you can give the methods different names.

0
source

Source: https://habr.com/ru/post/1332913/


All Articles