Java tutorial
//package com.java2s; /* * This file is part of McIDAS-V * * Copyright 2007-2015 * Space Science and Engineering Center (SSEC) * University of Wisconsin - Madison * 1225 W. Dayton Street, Madison, WI 53706, USA * http://www.ssec.wisc.edu/mcidas * * All Rights Reserved * * McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and * some McIDAS-V source code is based on IDV and VisAD source code. * * McIDAS-V is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * McIDAS-V is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with this program. If not, see http://www.gnu.org/licenses. */ import java.util.Collection; import java.util.Iterator; import java.util.Map; public class Main { /** * Determines the {@literal "length"} of a given object. This method * currently understands:<ul> * <li>{@link Collection}</li> * <li>{@link Map}</li> * <li>{@link CharSequence}</li> * <li>{@link Array}</li> * <li>{@link Iterable}</li> * <li>{@link Iterator}</li> * </ul> * * <p>More coming! * * @param o {@code Object} whose length we want. Cannot be {@code null}. * * @return {@literal "Length"} of {@code o}. * * @throws NullPointerException if {@code o} is {@code null}. * @throws IllegalArgumentException if the method doesn't know how to test * whatever type of object {@code o} might be. */ @SuppressWarnings({ "WeakerAccess" }) public static int len(final Object o) { if (o == null) { throw new NullPointerException("Null arguments do not have a length"); } if (o instanceof Collection<?>) { return ((Collection<?>) o).size(); } else if (o instanceof Map<?, ?>) { return ((Map<?, ?>) o).size(); } else if (o instanceof CharSequence) { return ((CharSequence) o).length(); } else if (o instanceof Iterator<?>) { int count = 0; Iterator<?> it = (Iterator<?>) o; while (it.hasNext()) { it.next(); count++; } return count; } else if (o instanceof Iterable<?>) { return len(((Iterable<?>) o).iterator()); } throw new IllegalArgumentException("Don't know how to find the length of a " + o.getClass().getName()); } }