Java tutorial
//package com.java2s; /** * <copyright> * * Copyright (c) 2006, 2008 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: * IBM - Initial API and implementation * * </copyright> * * $Id: CollectionUtil.java,v 1.5 2008/03/26 21:17:25 cdamus Exp $ */ import java.util.Collection; import java.util.Iterator; public class Main { /** * Implementation of the OCL * <ul> * <li><tt>OrderedSet::at(index : Integer) : T</tt></li> * <li><tt>Sequence::at(index : Integer) : T</tt></li> * </ul> * operations. * * @param self the source collection * @param index the 1-based (in OCL fashion) index * @return the object at the specified index of the source collection */ public static <E> E at(Collection<E> self, int index) { index = index - 1; if (index < 0 || index >= self.size()) { return null; // undefined } int curr = 0; for (Iterator<E> it = self.iterator(); it.hasNext();) { E object = it.next(); if (curr++ == index) { return object; } } return null; // undefined } }