Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

collection

 
AJ sisodia
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;

class Address
{
private String name;
private String street;
private String city;

Address(String n, String s, String c)
{
name=n;
street=s;
city=c;
}
public String toString()
{
return name + "\n" + street + " \n" + city;
}
}

class UtilDemo
{
public static void main(String args[])
{
LinkedList L = new LinkedList();
L.add(new Address("Gili","11 Oak","L.A"));
L.add(new Address("Josh","97 JK avenue","Delhi"));
L.add(new Address("ritu","Bahadurgarh","HAryana"));

Iterator I= L.iterator();
while(I.hasNext())
{
Object O = I.next();
System.out.println(O + "\n");
}
}
}

Help!
can't make out why are we using toString() method here and if not used why the program returns value like Address5437@*&()%^.

Could you help me understand Map.Entry by giving simple examples.(Please)
 
karthikeyan Chockalingam
Ranch Hand
Posts: 259
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Below is the java doc for toString() method in Object. Hence we are using toString method to override inorder to ptovide a concise but informative representation that is easy for a person to read.

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is called overriding a method because the toString() method is already implemented in the Object superclass. However, this default implementation is typically not very helpful since it only gives the name of the class and some numerical value that represents the instance of the class.

However, you might wonder where the toString() method is even executed. It is hidden inside this line:

When you use the + operator with a String and an Object, the toString() method on the Object is called. By a mechanism called "polymorphism", the toString() method that is defined in the Address class will be called here.

I hope this helps.

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic