0
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..

1
  • 1
    Which API documentation are you looking at? Because this is pretty clear. Commented Mar 6, 2015 at 16:48

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, bad link. I fixed it.
0

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(' ');
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.