1 /*******************************************************************************
2 * Copyright (c) 2007, 2010 Association for Decentralized Information Management
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v1.0
6 * which accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
10 * VTT Technical Research Centre of Finland - initial API and implementation
11 *******************************************************************************/
12 package org.simantics.utils.datastructures;
14 import java.util.Collection;
15 import java.util.Iterator;
18 * Collection with at most 2 elements. Does not use equals for comparison.
20 public class Max2Collection<T> implements Collection<T> {
25 static class CollectionIsFullException extends RuntimeException {
27 private static final long serialVersionUID = 8693601196559590064L;
31 public Max2Collection() {
34 public Max2Collection(T first, T second) {
39 public Max2Collection(T first) {
43 final public T get(int i) {
49 throw new IndexOutOfBoundsException();
52 final public T getOther(T el) {
59 final public boolean add(T el) {
62 else if(second == null)
65 throw new CollectionIsFullException();
69 final public boolean remove(Object el) {
75 else if(second == el) {
83 final public void setFirstElement(T el) {
90 final public void setSecondElement(T el) {
98 final public int size() {
101 else if(second == null)
107 final public boolean isEmpty() {
108 return first == null;
111 final public boolean isFull() {
112 return second != null;
116 public boolean addAll(Collection<? extends T> c) {
123 public void clear() {
125 second = null; // necessary for gc
129 public boolean contains(Object o) {
130 return first == o || second == o;
134 public boolean containsAll(Collection<?> c) {
142 public Iterator<T> iterator() {
143 throw new UnsupportedOperationException();
147 public boolean removeAll(Collection<?> c) {
148 boolean removed = false;
150 removed |= remove(o);
155 public boolean retainAll(Collection<?> c) {
156 throw new UnsupportedOperationException();
160 public Object[] toArray() {
162 return new Object[0];
164 return new Object[] {first};
166 return new Object[] {first, second};
169 @SuppressWarnings("hiding")
171 public <T> T[] toArray(T[] a) {
172 throw new UnsupportedOperationException();