Java tutorial
//package com.java2s; /******************************************************************************* * Copyright (c) 2006, 2014 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mike Kucera (IBM Corporation) - initial API and implementation * Sergey Prigogin (Google) * Nathan Ridge *******************************************************************************/ import java.util.Iterator; import java.util.List; public class Main { /** * Finds the first object in the heterogeneous list that is an instance of * the given class, removes it from the list, and returns it. * If there is not object in the list of the given type the list is left * unmodified and null is returned. * * @throws NullPointerException if list or clazz is null * @throws UnsupportedOperationException if the list's Iterator does not support the remove() * method */ @SuppressWarnings("unchecked") public static <T> T findFirstAndRemove(List<?> list, Class<T> clazz) { for (Iterator<?> iter = list.iterator(); iter.hasNext();) { Object o = iter.next(); if (clazz.isInstance(o)) { iter.remove(); return (T) o; // safe } } return null; } }