1

I just recently upgraded my local JDK to Java 11. I see java 9 got upgraded with some static methods in List/Map class -> of().

question is why do we need overloaded methods? We have at least 6/7 methods and one of them takes in var-args which will work for 2,3,4 any number of entries for which Java has defined overloaded methods?

Any particular reason behind this?

Thanks.

Naman
  • 27,789
  • 26
  • 218
  • 353
Priyak Dey
  • 1,227
  • 8
  • 20
  • More appropriate title should be - Overloaded static factory method of List/Map in Java 9. I do not see a update option? If any mod can, please will you update. Thanks – Priyak Dey Mar 18 '20 at 13:42
  • Thanks @NathanHughes – Priyak Dey Mar 18 '20 at 13:45
  • `Map.of(key1, value1, key2, value2)` cannot be done with varargs, because you have two types (for key and value) and the number of arguments must be even. Varargs cannot express that. – Thilo Mar 18 '20 at 13:57
  • 1
    For `List.of` see related threads https://stackoverflow.com/q/49403644/14955 and https://stackoverflow.com/q/45791676/14955 – Thilo Mar 18 '20 at 13:59
  • I mean var-args is kind of generalized term I have used. If you see the code for Map.class, they have handled with var-args of Map.Entry. My question is - if you see overloaded methods - there is one for taking 1element, 2 elements.... 6 elements and then another overloaded method takes in var-args. So why the overloaded methods? We can enter 1/2/3.....N elements with var-args concept, why the need for overloading them with specific use cases ? – Priyak Dey Mar 18 '20 at 14:01
  • Thanks @Thilo, answers my question. even I thought it to be just a design decision. Thanks for the links – Priyak Dey Mar 18 '20 at 14:03
  • That's just developer ergonomics. Java has gotten a pretty bad rap for all the boilerplate that it makes people write. `Map.of(x,y,z,a,b,c)` reads much better than `Map.of(Pair.of(x,y), Pair.of(z,a), Pair.of(b,c))` (and that's already a big step up from the pre-Java-8 `Map x =new HashMap(); x.put(a,b); ... ` – Thilo Mar 18 '20 at 14:03
  • @Thilo, I am pretty new here. Any chance I can block answers to this question cause you already shared pretty much all I needed to know ? Or do I have to delete the post entirely ? – Priyak Dey Mar 18 '20 at 14:05
  • 1
    No, leave it open. It's a good question. Someone will write up an answer. Everyone gets upvotes. People find this on Google when they have the same query. Happiness all around. – Thilo Mar 18 '20 at 14:06
  • 2
    @PriyakDey You can answer your own question on SO, and in this case it seems entirely appropriate for you to write and accept your own answer. Please don't feel uncomfortable doing this; for several reasons it is more helpful to the community to have a solution in an accepted answer rather than in a group of comments. – skomisa Mar 18 '20 at 15:00

0 Answers0