0

I am new to java and am trying to write a method that will print out an ArrayList using an enhanced for loop. Whenever I compile, the fore loop gives me the following errors:

error: cannot find symbol

error: variable list2 is already defined in method printLists(ArrayList,ArrayList) for(String list2: list)

public static void printLists(ArrayList <String> list1, ArrayList <String> list2 )
{
    System.out.println("list1.txt contains:");
    for(String list1: list)
        System.out.println(list1+ " ");

    System.out.println("list2.txt contains:");
    for(String list2: list)
        System.out.println(list2+ " ");
}

Can someone please explain to me what these errors mean?

Gilad Green
  • 36,708
  • 7
  • 61
  • 95
starlight
  • 130
  • 1
  • 18

2 Answers2

4

The use of the for-each loop is incorrect:

for(String list1: list)

Two problems with this line:

  1. As error says you are trying to define a new variable names list1 of type String but you already have such a variable name in the scope.
  2. There is nothing defined as list. Basically the syntax is that: for(#item : #collection)

You are looking for something like

for(String item : list1)

Read more on How does the Java 'for each' loop work?


A nicer way to print list will be to use String.join as seen here

System.out.println(String.join(" ", list1));
Gilad Green
  • 36,708
  • 7
  • 61
  • 95
1

You've swapped list and list1 (and list2) in your for-each loops. However, I would first suggest you program to the List interface. And assuming you are using Java 8+, I would prefer to stream() the contents and join them with a Collector. Like,

public static void printLists(List<String> list1, List<String> list2) {
    System.out.printf("list1.txt contains: %s%n", list1.stream()
            .collect(Collectors.joining(" ")));
    System.out.printf("list2.txt contains: %s%n", list2.stream()
            .collect(Collectors.joining(" ")));
}

or possibly make the arguments variadic and generic (so it can take any number of Lists of any type) like

@SafeVarargs
public static <T> void printLists(List<T>... lists) {
    for (int i = 0; i < lists.length; i++) {
        System.out.printf("list%d.txt contains: %s%n", i + 1,
                lists[i].stream().map(Object::toString).collect(
                        Collectors.joining(" ")));
    }
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249