toString() Generator: Content Listing

This topic discusses how toString() generator lists contents of arrays and how it limits number of items listed in Collections and Maps. Used method depends not only on the member type, but also on selected JDK compatibility of the project.

Listing contents of Arrays

Listing limited contents of Lists

The same solution is used for all JDK versions: aList.subList(0, Math.min(aList.size(), maxLen))

Listing limited contents of Collections (helper method)

A Collection cannot be turned into a List without copying its contents (assuming it isn't a List already), so a helper method is used to iterate over first maxLen elements and build a string out of them:

private String toString(Collection collection, int maxLen) {
	StringBuffer stringBuffer = new StringBuffer();
	stringBuffer.append("[");
	int i = 0;
	for (Iterator iterator = collection.iterator(); iterator.hasNext() && i < maxLen; i++) {
		if (i > 0)
			stringBuffer.append(", ");
		stringBuffer.append(iterator.next());
	}
	stringBuffer.append("]");
	return stringBuffer.toString();
}
NOTES:

Listing limited contents of Maps

In case of Maps, the same helper method is used as for Collections only that map.entrySet() is passed to it.

Summary

This table sums up what methods are used in different conditions:

java.util.List java.util.Collection java.util.Map Array of primitive type Array of non-primitive type
jdk 1.4 - - - helper method arrayToString(array, len) Arrays.asList(array)
jdk 1.4/1.5, limit elements member.subList() helper method toSting(collection, maxLen) helper method toString(collection, maxLen) with map.entrySet() helper method arrayToString(array, len, maxLen) Arrays.asList(array).subList()
jdk 1.5 - - - Arrays.toString() Arrays.asList(array)
jdk 1.6 - - - Arrays.toString() Arrays.toString()
jdk 1.6, limit elements member.subList() helper method toString(Collection) helper method toString(Collection) with map.entrySet() Arrays.toString(Arrays.copyOf(member, ...)) Arrays.asList(array).subList()

Additional notes

Related reference

Generate toString() dialog
toString() Generator: Format Templates
toString() Generator: Code Styles