org.eclipse.jetty.util.LazyList Maven / Gradle / Ivy
The newest version!
//
// ========================================================================
// Copyright (c) 1995-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.util;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/* ------------------------------------------------------------ */
/** Lazy List creation.
* A List helper class that attempts to avoid unnecessary List
* creation. If a method needs to create a List to return, but it is
* expected that this will either be empty or frequently contain a
* single item, then using LazyList will avoid additional object
* creations by using {@link Collections#EMPTY_LIST} or
* {@link Collections#singletonList(Object)} where possible.
*
* LazyList works by passing an opaque representation of the list in
* and out of all the LazyList methods. This opaque object is either
* null for an empty list, an Object for a list with a single entry
* or an {@link ArrayList} for a list of items.
*
*
Usage
*
* Object lazylist =null;
* while(loopCondition)
* {
* Object item = getItem();
* if (item.isToBeAdded())
* lazylist = LazyList.add(lazylist,item);
* }
* return LazyList.getList(lazylist);
*
*
* An ArrayList of default size is used as the initial LazyList.
*
* @see java.util.List
*/
public class LazyList
implements Cloneable, Serializable
{
private static final String[] __EMTPY_STRING_ARRAY = new String[0];
/* ------------------------------------------------------------ */
private LazyList()
{}
/* ------------------------------------------------------------ */
/** Add an item to a LazyList
* @param list The list to add to or null if none yet created.
* @param item The item to add.
* @return The lazylist created or added to.
*/
@SuppressWarnings("unchecked")
public static Object add(Object list, Object item)
{
if (list==null)
{
if (item instanceof List || item==null)
{
List