Wrote a method that should output through recursion (using the collection iterator) all the elements of a list separated by a given character as a string. For example, there is a list that contains numbers from 1 to 5. When you call the join method, this list should be displayed in the format "1 + 2 + 3 + 4 + 5". In general, the method works, but for some reason, as a result, I get "1 + 2 + 3 + 4 + 5 +". Where am I mistaken that I have another plus after 5?
public static String join(List values, String separator) { return join(values.iterator(), separator); } public static String join(Iterator values, String separator) { if (!values.hasNext()) return ""; String firstElement = values.next() + separator; // Первый элемент списка String restElements = join(values, separator); return firstElement + restElements; }