/*
 * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * $Id$ 
 */
package com.sun.ts.tests.jaxrs.common.util;

import java.util.Iterator;
import java.util.LinkedList;

/**
 * Hold multiple instances of TYPE in a {@link LinkedList} structure, last one
 * accessible by {@link #get()}. 
 * 
 * @param <TYPE>
 */
public class LinkedHolder<TYPE> extends Holder<TYPE> implements Iterable<TYPE> {

	private LinkedList<TYPE> list = new LinkedList<TYPE>();

	public LinkedHolder(TYPE type) {
		add(type);
	}

	public LinkedHolder() {
	}

	public void add(TYPE value) {
		list.add(value);
		super.set(value);
	}

	/**
	 * Replace the last item in the list
	 */
	@Override
	public void set(TYPE value) {
		if (list.size() != 0) {
			list.set(list.size() - 1, value);
			super.set(value);
		} if (value == null) {
			super.set(null);
		} else { 
			add(value);
		}
	}

	public TYPE get(int index) {
		if (index >= list.size())
			return null;
		return list.get(index);
	}

	public int size() {
		return list.size();
	}
	
	public void clear() {
		super.set(null);
		list.clear();
	}

	@Override
	public Iterator<TYPE> iterator() {
		return list.iterator();
	}

	public LinkedList<TYPE> asList() {
		return list;
	}

}
