001 /*
002 Copyright (c) 2009 Olivier Chafik, All Rights Reserved
003
004 This file is part of JNAerator (http://jnaerator.googlecode.com/).
005
006 JNAerator is free software: you can redistribute it and/or modify
007 it under the terms of the GNU General Public License as published by
008 the Free Software Foundation, either version 3 of the License, or
009 (at your option) any later version.
010
011 JNAerator is distributed in the hope that it will be useful,
012 but WITHOUT ANY WARRANTY; without even the implied warranty of
013 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
014 GNU General Public License for more details.
015
016 You should have received a copy of the GNU General Public License
017 along with JNAerator. If not, see <http://www.gnu.org/licenses/>.
018 */
019 package com.ochafik.util;
020 import java.util.AbstractCollection;
021 import java.util.Collection;
022 import java.util.Iterator;
023 public class CollectionAdapter<U,V> extends AbstractCollection<V> {
024 protected Collection<U> collection;
025 protected Adapter<U,V> adapter;
026 public CollectionAdapter(Collection<U> collection,Adapter<U,V> adapter) {
027 this.collection=collection;
028 this.adapter=adapter;
029 }
030 @Override
031 public Iterator<V> iterator() {
032 return new IteratorAdapter(collection.iterator());
033 }
034 @Override
035 public int size() {
036 return collection.size();
037 }
038 @Override
039 public boolean isEmpty() {
040 return collection.isEmpty();
041 }
042 @Override
043 public void clear() {
044 collection.clear();
045 }
046 @Override
047 public boolean add(V o) {
048 return collection.add(adapter.reAdapt(o));
049 }
050 @Override
051 public boolean contains(Object o) {
052 for (U element : collection) {
053 if (adapter.adapt(element).equals(o)) {
054 return true;
055 }
056 }
057 return false;
058 }
059 protected class IteratorAdapter implements Iterator<V> {
060 Iterator<U> iterator;
061 public IteratorAdapter(Iterator<U> iterator) {
062 this.iterator=iterator;
063 }
064 public boolean hasNext() {
065 return iterator.hasNext();
066 }
067 public V next() {
068 return adapter.adapt(iterator.next());
069 }
070 public void remove() {
071 iterator.remove();
072 }
073 }
074 /*protected abstract V adapt(U value);
075 protected U reAdapt(V value) {
076 throw new UnsupportedOperationException();
077 }*/
078 }