You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@commons.apache.org by bu...@apache.org on 2004/04/01 14:49:22 UTC

DO NOT REPLY [Bug 27909] - [PATCH] add size(Object) to CollectionsUtil

DO NOT REPLY TO THIS EMAIL, BUT PLEASE POST YOUR BUG 
RELATED COMMENTS THROUGH THE WEB INTERFACE AVAILABLE AT
<http://issues.apache.org/bugzilla/show_bug.cgi?id=27909>.
ANY REPLY MADE TO THIS MESSAGE WILL NOT BE COLLECTED AND 
INSERTED IN THE BUG DATABASE.

http://issues.apache.org/bugzilla/show_bug.cgi?id=27909

[PATCH] add size(Object) to CollectionsUtil





------- Additional Comments From smelzer@paymentech.com  2004-04-01 12:49 -------
i appreciate the additional changes.  i hadn't given any thought to iterators 
or enumerations.  good add.

i added one more check at the last else to check for primitive arrays (you 
can't do a general instanceof so i am using a try-catch block instead).

	public static int size(Object object) {
		int total = 0;
		if (object instanceof Map) {
			total = ((Map) object).size();
		} else if (object instanceof Collection) {
			total = ((Collection) object).size();
		} else if (object instanceof Object[]) {
			total = ((Object[]) object).length;
		} else if (object instanceof Iterator) {
			Iterator it = (Iterator) object;
			while (it.hasNext()) {
				total++;
				it.next();
			}
		} else if (object instanceof Enumeration) {
			Enumeration it = (Enumeration) object;
			while (it.hasMoreElements()) {
				total++;
				it.nextElement();
			}
		} else {
			try {
				total = Array.getLength(object);
			} catch(IllegalArgumentException e) {
				throw new IllegalArgumentException("Unsupported 
object type: " +
					(object == null ? "null" : 
object.getClass().getName()));
			}
		}
		return total;
	}

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org