Java tutorial
//package com.java2s; /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved. * * The contents of this file are subject to the terms of the GNU General Public License Version 3 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each file. */ import java.util.List; public class Main { /** * Return an index between <code>0</code> and <code>l.size()</code> inclusive. If <code>i</code> * is negative, it is added to <code>l.size()</code> (but bounded to 0), ie for a list of 3 * items, -1 is the index of the last item ; -3 and -4 are both the first. If <code>i</code> is * greater than <code>l.size()</code> then <code>l.size()</code> is returned. * * <pre> * a b c a b c * -3 -2 -1 0 1 2 3 * </pre> * * @param l the list, eg a list of 3 items. * @param i the virtual index, eg -1. * @return the real index, eg 2. */ static public int getValidIndex(final List<?> l, final int i) { return getValidIndex(l, i, false); } static public int getValidIndex(final List<?> l, final int i, final boolean strict) { final int size = l.size(); if (i > size) { if (strict) throw new IndexOutOfBoundsException("Too high : " + i + " > " + size); return size; } else if (i < -size) { if (strict) throw new IndexOutOfBoundsException("Too low : " + i + " < " + -size); return 0; } else if (i >= 0) { return i; } else { return size + i; } } }