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
17 public class CollectionAdapter<Domain, Range, C extends Collection<Domain>>
\r
18 implements Collection<Range> {
\r
20 protected Converter<Domain, Range> converter;
\r
21 protected C collection;
\r
23 public CollectionAdapter(Converter<Domain, Range> converter, C collection) {
\r
24 this.converter = converter;
\r
25 this.collection = collection;
\r
28 public boolean add(Range e) {
\r
29 return collection.add(converter.convertFrom(e));
\r
31 @SuppressWarnings("unchecked")
\r
33 public boolean addAll(Collection<? extends Range> c) {
\r
34 return collection.addAll(new CollectionAdapter<Range, Domain, Collection<Range>>(inverseConverter(converter), (Collection<Range>)c));
\r
37 public void clear() {
\r
40 @SuppressWarnings("unchecked")
\r
42 public boolean contains(Object o) {
\r
43 return collection.contains(converter.convertFrom((Range)o));
\r
46 public boolean containsAll(Collection<?> c) {
\r
53 public boolean isEmpty() {
\r
54 return collection.isEmpty();
\r
57 public Iterator<Range> iterator() {
\r
58 return new IteratorAdapter<Domain, Range, Iterator<Domain>>(converter, collection.iterator());
\r
60 @SuppressWarnings("unchecked")
\r
62 public boolean remove(Object o) {
\r
63 return collection.remove(converter.convertFrom((Range)o));
\r
66 public boolean removeAll(Collection<?> c) {
\r
67 boolean removed = false;
\r
69 removed |= remove(o);
\r
72 @SuppressWarnings("unchecked")
\r
74 public boolean retainAll(Collection<?> c) {
\r
76 return collection.retainAll(new CollectionAdapter<Range, Domain, Collection<Range>>(inverseConverter(converter), (Collection<Range>)c));
\r
80 return collection.size();
\r
83 public Object[] toArray() {
\r
84 Object[] ret = new Object[collection.size()];
\r
86 for(Domain d : collection)
\r
87 ret[i++] = converter.convertTo(d);
\r
91 public <T> T[] toArray(T[] a) {
\r
92 throw new UnsupportedOperationException();
\r
95 public static <D,R> Converter<R,D> inverseConverter(final Converter<D,R> converter) {
\r
96 return new Converter<R,D>() {
\r
99 public R convertFrom(D rangeElement) {
\r
100 return converter.convertTo(rangeElement);
\r
104 public D convertTo(R domainElement) {
\r
105 return converter.convertFrom(domainElement);
\r