Lists

ArrayList keeps order and can grow.

List is an interface, ArrayList is the usual implementation. A list keeps order and allows duplicates. Indexes start at zero. get with a bad index throws IndexOutOfBoundsException; it does not return null. Here you must not confuse "there is no element" with "the element is there, but it is null".

The size is size(), not a field. Adding to the end is cheap. Inserting at the start shifts the tail. If you constantly need both the start and the end, look at a different structure instead of patching ArrayList by hand.

String.join(",", list) builds the text without a hand-written loop and without a stray comma. It is simpler than a flag that says "I have already printed a comma". For an empty list the result is an empty string.

Declare the variable as List and create an ArrayList. Calling code then does not stick to the implementation. In the task method you can create a list, add two words and return them separated by a comma.

Practice

  1. Which index first

    At which index does an ArrayList start?

    • 0
    • 1
    • -1
    • it depends on the JDK
  2. Joining

    The list holds the words go and java. They were joined with a comma and no space. Write the resulting line.

  3. Two words

    Write static String join(String a, String b). Put the words into a list in this order and return them separated by a comma with no space.