Reputation: 585
The ArrayList, below, successfully prints its objects' fields, when the ArrayLists's reference variable "goes inside" System.out.println().
The output: [Dal:Tigers, SMU:Tigers, Acadia:Axemen]
The second ArrayList fails to print its objects' fields when its ArrayList reference "goes inside" System.out.println()...
why? I was surprised to even learn that an ArrayList's members could be printed by using an output method on the ArrayList's reference variable. What difference is there between the second code and the first one?
USport class:
import java.util.ArrayList;
class USport {
String school; // creates a field for String
String name; // creates a field for name
public USport( String s, String n) // initializes school and name
{school = s;
name = n;}
public String toString () // for use in output method; returns both
{return school + ":" + name;}
}
public class ArrayListDemo {
public static void main(String a[]) {
ArrayList <USport> v = new ArrayList <> ();
v.add( new USport ("Dal", "Tigers"));
v.add( new USport ("SMU", "Tigers"));
v.add( new USport ("Acadia", "Axemen"));
System.out.println(v);
}
}
Cities class:
import java.util.ArrayList;
public class Cities {
private String pub;
private boolean pubHasDancing;
public Cities(String pub, boolean pubHasDancing){
this.pub = pub;
this.pubHasDancing = pubHasDancing;
}
public static void main(String[]args){
ArrayList <Cities> list2 = new ArrayList <> ();
list2.add(new Cities ("Joce McCartney", false));
list2.add(new Cities ("Paul McCartney", true));
System.out.println(list2); // <<<<<< This is the method I'm questioning
System.out.println(list2.get(1).pub);
System.out.println(list2.toString()); /** <<<< This output should be the same as println's output no */
}
}
Upvotes: 0
Views: 83
Reputation: 11971
The difference is: In the first class, you override the toString()
method. However, you didn't do that in the second class. The System.out.println()
will invoke the ArrayList
's toString
method, which will invoke the toString()
method of AbstractCollection
class. So you need to override the toString()
method of the second class in order to get the correct output.
@Override
public String toString () {
return pub + ":" + pubHasDancing;
}
Upvotes: 2
Reputation: 11030
Because USport
declares a toString()
method that does the printing, and Cities
doesn't.
Upvotes: 3