Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]
like image 621
ICG Avatar asked Nov 30 '22 20:11

ICG


2 Answers

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;

like image 88
jlordo Avatar answered Dec 06 '22 06:12

jlordo


java.awt.List is List component (like drop down list as you would see in a GUI) (source.)

A drop down list

Where java.util.List is an ordered collection for you to store your data. (source)

Try changing your import (as jlordo mentioned) from

import java.awt.List;

to

import java.util.List;
like image 39
darkwisperer Avatar answered Dec 06 '22 06:12

darkwisperer