Home > Back-end >  How does the toString method display an entire list of objects without iterating a loop?
How does the toString method display an entire list of objects without iterating a loop?

Time:12-21

Well, I'm starting to study Java now and the following question came up, if I have a list of objects, and I override the toString method, as java can show all the values of the objects in the list, without iterating with some kind of for ?

import java.util.List;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
         List<AB> p = new ArrayList<>();
         p.add(new AB("tst1", 25));
         p.add(new AB("tst2", 22));
         System.out.println(p);    
    }
}

public class AB {
                
      String name;
      int age;

      public AB(String name, int age) {
          this.name = name;
          this.age = age;
      }

      public String toString() {
           return name   " "   age;
      }
}

So my question is I'm not actually stepping through objects as all object values are displayed using toString ?

CodePudding user response:

ArrayList extends from AbstractList which extends from AbstractCollection which overrides the toString method (defined in Object)

This then iterates over the list of elements, calling their toString methods which, in the end, generates the String

public String toString() {
    Iterator<E> it = iterator();
    if (! it.hasNext())
        return "[]";

    StringBuilder sb = new StringBuilder();
    sb.append('[');
    for (;;) {
        E e = it.next();
        sb.append(e == this ? "(this Collection)" : e);
        if (! it.hasNext())
            return sb.append(']').toString();
        sb.append(',').append(' ');
    }
}
  • Related