Created
June 11, 2014 17:31
-
-
Save louiszuckerman/ad9908cff91a80bf825d to your computer and use it in GitHub Desktop.
TreeSet with lower & upper bounds
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Collection; | |
import java.util.Comparator; | |
import java.util.TreeSet; | |
public class BoundedTreeSet<T> extends TreeSet<T> { | |
private T min, max; | |
public BoundedTreeSet(Comparator<T> comparator, T min, T max) { | |
super(comparator); | |
this.min = min; | |
this.max = max; | |
} | |
@Override | |
public boolean addAll(Collection<? extends T> c) { | |
Comparator<? super T> comparator = comparator(); | |
if (null != comparator && null != min && null != max) { | |
boolean changed = false; | |
for (T t : c) { | |
changed |= add(t); | |
} | |
return changed; | |
} else { | |
return super.addAll(c); | |
} | |
} | |
@Override | |
public boolean add(T t) { | |
Comparator<? super T> comparator = comparator(); | |
if (null != comparator && null != min && null != max) { | |
if (comparator.compare(t, min) < 0) { | |
return false; | |
} | |
if (comparator.compare(t, max) > 0) { | |
return false; | |
} | |
} | |
return super.add(t); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment