A List of Strings

exercise No. 173

Inserting strings into a List. Create comment in forum

Q:

Create a List of String instances including duplicates. Iterate over this list and write each value to System.out:

public static void main(String[] args) {

  final List<String>  names =  ...;

  names.add(...
     ...

  // Iterate over all inserted strings
  System.out.println("The list contains " + names.size() + " elements:");
  for (final String s : names) {
    System.out.println(s);
  }
}

A:

Our code closely resembles Inserting strings into a Set. :

public static void main(String[] args) {

  final List<String>  names =  new Vector<String>();

  names.add("Eve");
  names.add("Jim");
  names.add("Tom");
  names.add("Jim");

  // Iterate over all inserted strings
  System.out.println("The list contains " + names.size() + " elements:");
  for (final String s : names) {
    System.out.println(s);
  }
}

This time the duplicate actually shows up:

The list contains 4 elements:
Eve
Jim
Tom
Jim