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