0

I am dealing with ellipsis (...) in method parameters in java. The situation is as follows: I fill a Map and do calculations with it, as shown in the code below, but there is 1 method (addAllMood) that must be executed with different parameters in this method (either accept nothing or accept Map)

Map<MOOD, Float> map;
    LocalDate currentDay = LocalDate.now();
    LocalDate startDay = currentDay.minusDays(period.getDays());
    try {
            map = this.messageDao.getMoodStatistics(startDay, currentDay);
    } catch (EmptyResultDataAccessException e) {
        map = addAllMood();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    addAllMood(map);
    return map;
}
private Map addAllMood(Map... map) {
    for (MOOD mood : MOOD.values()) {
        if (map.get(mood) == null) {
            map.put(mood, 0);
        }
    }
    return map;
}

enter image description here Overloading is not considered, you need exactly the option with ... and Map. In the course of work, I had a question : Can I generally use a Map with ellipsis in a method parameter? If so, tell me how this can be done, I will be very grateful)

  • Have you tried actually running the code? I imagine compiler would be telling you what's wrong witht he current code – Deltharis Jul 26 '21 at 07:29
  • added to the screenshot in the post, it shows in red – Антон Павлецов Jul 26 '21 at 07:38
  • the problem is that with ellipsis, the compiler wants to return an array, not a map – Антон Павлецов Jul 26 '21 at 07:40
  • 1
    Well, yes. Because ellipsis is a fancy syntax to define an array as input. – Deltharis Jul 26 '21 at 07:41
  • so the question is, can I use a Map with ellipsis, if ida, how can I do it?) – Антон Павлецов Jul 26 '21 at 07:44
  • There is nothing special in Map ellipsis that's different from, say, String ellipsis. It's an array of maps. – Deltharis Jul 26 '21 at 07:45
  • Do you understand what the ellipsis mean? It's a way to specify that the method has a [variable number of arguments](https://www.baeldung.com/java-varargs). Do you really want to be able to pass multiple maps to the `addAllMood` method? It doesn't look like that's what you are looking for, so you shouldn't use the ellipsis. Also, you should use generics, and [not use raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it). – Jesper Jul 26 '21 at 07:59

0 Answers0