CKTIS / Java
AbstractCollection.toString — a collection's textual representation
AbstractCollection.toString returns elements in square brackets, following iterator order and separating them with a comma and a space.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public String toString()
collection.toString()AbstractCollection.toString is a public instance method returning String, with no arguments. It overrides Object.toString(). A subclass can inherit this implementation or override it.
The result has the form [element1, element2]: elements follow the order returned by iterator(), and the separator is ", ". An empty collection produces []. The method does not sort elements itself.
Element conversion generally follows String.valueOf(Object): null becomes the text null, and a non-null object's toString() is called. In the inherited OpenJDK 21 implementation, if an element directly references the collection itself, the method inserts (this Collection) instead of recursively calling the collection's toString(). This marker is an implementation detail, not a Java SE guarantee. Strings receive no additional quotation marks, so do not treat the result as a serialization format.
The example defines iterator() and size() in an anonymous subclass, leaving toString() inherited. The fixed data order makes [red, null, blue] the expected result.
Examples
import java.util.AbstractCollection;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Main {
public static void main(String[] args) {
AbstractCollection<String> values = new AbstractCollection<>() {
private final List<String> data = Arrays.asList("red", null, "blue");
@Override
public Iterator<String> iterator() {
return data.iterator();
}
@Override
public int size() {
return data.size();
}
};
System.out.println(values.toString());
}
}Result
[red, null, blue]
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.