View Javadoc

1   /*
2   	Copyright (c) 2009 Olivier Chafik, All Rights Reserved
3   	
4   	This file is part of JNAerator (http://jnaerator.googlecode.com/).
5   	
6   	JNAerator is free software: you can redistribute it and/or modify
7   	it under the terms of the GNU General Public License as published by
8   	the Free Software Foundation, either version 3 of the License, or
9   	(at your option) any later version.
10  	
11  	JNAerator is distributed in the hope that it will be useful,
12  	but WITHOUT ANY WARRANTY; without even the implied warranty of
13  	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  	GNU General Public License for more details.
15  	
16  	You should have received a copy of the GNU General Public License
17  	along with JNAerator.  If not, see <http://www.gnu.org/licenses/>.
18  */
19  package com.ochafik.util;
20  import java.util.AbstractCollection;
21  import java.util.Collection;
22  import java.util.Iterator;
23  public class CollectionAdapter<U,V> extends AbstractCollection<V> {
24  	protected Collection<U> collection;
25  	protected Adapter<U,V> adapter;
26  	public CollectionAdapter(Collection<U> collection,Adapter<U,V> adapter) {
27  		this.collection=collection;
28  		this.adapter=adapter;
29  	}
30  	@Override
31  	public Iterator<V> iterator() {
32  		return new IteratorAdapter(collection.iterator());
33  	}
34  	@Override
35  	public int size() {
36  		return collection.size();
37  	}
38  	@Override
39  	public boolean isEmpty() {
40  		return collection.isEmpty();
41  	}
42  	@Override
43  	public void clear() {
44  		collection.clear();
45  	}
46  	@Override
47  	public boolean add(V o) {
48  		return collection.add(adapter.reAdapt(o));
49  	}
50  	@Override
51  	public boolean contains(Object o) {
52  		for (U element : collection) {
53  			if (adapter.adapt(element).equals(o)) {
54  				return true;
55  			}
56  		}
57  		return false;
58  	}
59  	protected class IteratorAdapter implements Iterator<V> {
60  		Iterator<U> iterator;
61  		public IteratorAdapter(Iterator<U> iterator) {
62  			this.iterator=iterator;
63  		}
64  		public boolean hasNext() {
65  			return iterator.hasNext();
66  		}
67  		public V next() {
68  			return adapter.adapt(iterator.next());
69  		}
70  		public void remove() {
71  			iterator.remove();
72  		}
73  	}
74  	/*protected abstract V adapt(U value);
75  	protected U reAdapt(V value) {
76  		throw new UnsupportedOperationException();
77  	}*/
78  }