Privacy Policy Terms Of Use. Copyright © 2006-2010 Java Tutorials and Examples.
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.
- import java.util.ArrayList;
- //Java ArrayList toString
- public class JavaArrayListToString {
- public static void main(String args[]){
- ArrayList<Integer> aListNumbers = new ArrayList<Integer>();
- aListNumbers.add(1);
- aListNumbers.add(2);
- aListNumbers.add(3);
- /*
- * This will call toString method of Java ArrayList, which in turn
- * calls toString method of Integer wrapper class.
- *
- * toString method of Integer wrapper class outputs underlying int
- * value.
- */
- System.out.println(aListNumbers);
- //Create objects of custom Person class
- Person p1 = new Person("Alex", 29);
- Person p2 = new Person("Tanya", 21);
- //Create an ArrayList of objects Person
- ArrayList<Person> aListPersons = new ArrayList<Person>();
- //add Objects of Persons to ArrayList
- aListPersons.add(p1);
- aListPersons.add(p2);
- /*
- * This will call toString method of ArrayList class and in turn
- * it will call toString method of underlying class, that is in this
- * case Person class.
- *
- * If the Person class does not have toString defined, toString method
- * of Object class is called which prints default output similar to
- * as shown below.
- *
- * [Person@1c161c16, Person@1c1c1c1c]
- *
- * This kind of output is not useful, as we expect it to print
- * name and age of person added to ArrayList. In this case we can
- * override toString method of Person class.
- *
- */
- System.out.println(aListPersons);
- }
- }
- class Person{
- String name;
- int age;
- public Person(String name, int age){
- this.name = name;
- this.age = age;
- }
- public String getName(){
- return this.name;
- }
- public int getAge(){
- return this.age;
- }
- public String toString(){
- return this.getName() + "-" + this.getAge();
- }
- }
- /*
- Output of above given Java ArrayList toString method would be
- [Alex-29, Tanya-21]
- [1, 2, 3]
- */

WTF ,this is a manual
Post new comment