Skip to content

Instantly share code, notes, and snippets.

@ryankennedy
Created October 12, 2010 19:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryankennedy/622749 to your computer and use it in GitHub Desktop.
Save ryankennedy/622749 to your computer and use it in GitHub Desktop.
import java.util.*;
/**
* List implementation that facilitates wrapping an existing list to convert the contents to another type.
*
* <pre>
* List<String> stringList = Arrays.asList("0", "1", "2", "3", "4");
* List<Integer> integerList = new TypeAdaptingList<Integer, String>() {
* Integer adapt(String value) {
* return Integer.parseInt(value);
* }
* };
* </pre>
*
* @param <T> The type to adapt to.
* @param <U> The type to adapt from.
*/
public abstract class TypeAdaptingList<T,U> extends AbstractList<T> {
private List<U> toAdapt;
/**
* Constructs a new adapting list, converting the given list of type U to instances of T.
*
* @param toAdapt The list to adapt.
*/
public TypeAdaptingList(List<U> toAdapt) {
this.toAdapt = toAdapt;
}
@Override
public T get(int index) {
return adapt(toAdapt.get(index));
}
@Override
public int size() {
return toAdapt.size();
}
/**
* Adapting method to convert instances of type U to instances of type T.
*
* @param value The value of type U to be adapted.
* @return The adapted value of type T.
*/
public abstract T adapt(U value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment