Reputation: 17
class Employee
{
String name ;
// Constructor
Employee(String name) {
this.name = name;
}
// override toString method in Employee class
@Override
public String toString() {
return name;
}
}
public class TestArraylistIterator {
public static void main(String[] args) {
Employee obj1 = new Employee("Java");
Employee obj2 = new Employee("Microsoft");
TestArraylistIterator obj3 = new TestArraylistIterator();
List ls = new ArrayList();
ls.add(obj1);
ls.add(obj2);
System.out.println("List object :: " + ls);
System.out.println("TestArraylistIterator :: " + obj3);
}
}
output :
List object :: [Java, Microsoft]
TestArraylistIterator :: TestArraylistIterator@ad3ba4
So the Question is : If we try to print any object, it prints obj.getClass()+"@"+obj.hashCode(). But While printing the list object, it doesn't print the list object in the same way. Instead it looks like toString() is already overridden in ArrayList class. But didn't find anything like this in ArrayList API implementation. Any sugg is welcome..
Upvotes: 0
Views: 107
Reputation: 466
The method is overriden. If you decompile rt.jar (although you don't have to do this normally) you will see something like this:
public String toString() {
Iterator localIterator = iterator();
if (!localIterator.hasNext()) {
return "[]";
}
StringBuilder localStringBuilder = new StringBuilder();
localStringBuilder.append('[');
for (;;) {
Object localObject = localIterator.next();
localStringBuilder.append(localObject == this ? "(this Collection)" : localObject);
if (!localIterator.hasNext()) {
return ']';
}
localStringBuilder.append(',').append(' ');
}
}
Upvotes: 0
Reputation: 631
No, but it's overridden in AbstractCollection
, which ArrayList
is an indirect subclass of.
For future reference: when viewing the Java API docs, beneath the Method Summary, there can be several "Methods inherited from class SomeClass" sections. In the documentation for ArrayList
, it shows that toString()
is inherited from AbstractCollection
.
Upvotes: 5