这个程序中的 ArrayList 如何在没有任何循环的情况下打印元素?

How ArrayList in this program printing the elements without any loop?

下面的程序如何在不使用任何循环的情况下打印 ArrayList 中包含的元素

import java.util.*;  

class Abc{  
 public static void main(String args[]){  
  ArrayList<String> al=new ArrayList<String>();  
  al.add("Ravi");  
  al.add("Vijay");  
  al.add("Ravi");  
  al.add("Ajay");  

    System.out.println(al);  
 }  
}  

输出:[拉维、维杰、拉维、阿杰]

ArrayList 本身没有 toString() 方法。它扩展了 AbstractList,后者又扩展了 AbstractCollection,后者定义了实际的 'toString' 方法。

来自 java 文档:

toString

public String toString()

Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the order they are returned by its iterator, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (comma and space). Elements are converted to strings as by String.valueOf(Object).

Overrides:
toString in class Object
Returns:
a string representation of this collection

想到这行:

System.out.println(al);  

如实

System.out.println(al.toString());  

toString方法继承自AbstractCollection。

如果您对 AbstractCollection 的 toString 方法背后发生的事情感兴趣...

link: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractCollection.java#AbstractCollection.toString%28%29

它正在使用一个循环,但不是在您显示的代码中,而是在方法 toString()ArrayList 继承自 AbstractCollection ,它是其祖先之一 类.

每当您将对象传递给 print()println() 时,实际发生的是 print() 调用 String.valueOf() 将对象传递给它。

反过来,如果传递的对象不为空,则调用对象stoString` 方法。

AbstractCollection 有一个 toString 方法,它依赖于迭代和调用它所代表的集合中每个项目的 toString 方法。

所以那里有一个循环,但它被埋在一个调用方法的方法中。

因为 ArrayList 是用 Java 编写的,它有自己的实现。所以这就是为什么当你使用 toString() 然后它会打印你的元素。

但是,如果您尝试将 toString() 与 Array 一起使用,则它将不起作用。 因为数组是语言规范的一部分。

希望这对您有所帮助:)