Print a list in Java?
I want to print a list in Java
@H_ 301_ 8@
@H_ 301_ 8@
r1 r2 r3 r4
This is the code: @ h_ 301_ 8@
@H_ 301_ 8@
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 to make it print my list instead of: @ h_ 301_ 8@
@H_ 301_ 8@
java.awt.List[list0,0x0,invalid,selected=null]
Solution
In class, you have:
@H_ 301_ 8@
@H_ 301_ 8@
import java.awt.List;
However, Java awt. List describes a GUI component that may not be what you want To use the data structure list, change the import to: @ h_ 301_ 8@
@H_ 301_ 8@
import java.util.List;
Because Java util. List < E > is a universal interface, so you should also use it correctly: @ h_ 301_ 8@
@H_ 301_ 8@
List<String> list = new ArrayList<>();
Expression system out. println(list); The list object is printed, which may or may not display content (depending on the implementation of toString) To display the contents of the list, you need to iterate: @ h_ 301_ 8@
@H_ 301_ 8@
for ( String str : list ) { System.out.println(str); }
As described in the comments, this solution is only available if you also import Java util. It is valid only when ArrayList@ H_ 301_ 8@