javalistprinting

Print a list in Java?


I would like to print a List in Java.

r1
r2
r3
r4

Here is the code:

public static final void main(String args[]) {

    Scanner a = new Scanner(System.in);

    String r1, r2, r3, r4;

    System.out.print("Enter word..");
    r1 = a.next();

    System.out.print("Enter second word");
    r2 = a.next();

    System.out.print("Enter third word");
    r3 = a.next();

    System.out.print("Enter last word");
    r4 = a.next();

    List list = new List();
    list.add(r1);
    list.add(r2);
    list.add(r3);
    list.add(r4);

    System.out.println(list);
}

How do I get it print my list rather then:

java.awt.List[list0,0,0,0x0,invalid,selected=null]

Solution

  • On top of your class you have:

    import java.awt.List;
    

    However, java.awt.List describes a GUI component and is probably not what you want. To use the data structure List change the import to:

    import java.util.List;
    

    Since java.util.List<E> is a generic interface, you should also use it appropriately:

    List<String> list = new ArrayList<>();
    

    The expression System.out.println(list); will print the List object which may or may not show the contents (depending on the implementation of toString). To display the contents of the list, it will need to be iterated:

    for ( String str : list ) {
        System.out.println(str);
    }
    

    As noted in the comment, this solution will only work if you also import java.util.ArrayList;