【发布时间】:2017-02-08 10:42:01
【问题描述】:
我正在尽我所能制作数据结构:
- 添加带有开始和结束位置的对
- 可以得到对测试的列表
- 有间隙的间隔
例如添加 (0,2),(0,1),(3,4),(6,8) 它将返回 (0,4),(6,8) 检查(2,4) - 真 check(3,8) - false,因为 4 和 6 之间有一个差距。
如何修改下面的代码,例如设置list 和列表data 将包含原始int 而不是对象Integer?
编辑:我知道 java 泛型不能是原语,所以 List 是不可能的。我的动力来自于其他数据结构的实现。
例如 HashMap 与 android SparseArray 基本相同,不同之处在于 SparseArray 使用整数而不是整数作为键。
public class GapAwareList {
Set<Integer> list = new HashSet<>();
public void put(int start, int end) {
for (int i = start; i <= end; i++) {
list.add(i);
}
}
public void remove(int start, int end) {
for (int i = start; i <= end; i++) {
list.remove(i);
}
}
public List<Pair<Integer, Integer>> getPairs() {
List<Integer> data = new ArrayList<>();
data.addAll(list);
Collections.sort(data);
List<Pair<Integer, Integer>> pairs = new ArrayList<>();
int last = data.get(data.size() - 1);
int s = -1;
int e;
for (int i = 0; i <= last; i++) {
if (list.contains(i)) {
if (s == -1) {
s = i;
}
e = i;
if (!list.contains(i + 1)) {
Pair<Integer, Integer> p = new Pair<>(s, e);
pairs.add(p);
s = -1;
}
}
}
return pairs;
}
public boolean haveGap(int start, int end) {
boolean b = false;
for (int i = start; i < end; i++) {
if (!list.contains(i)) {
b = true;
break;
}
}
return b;
}
}
public class Pair {
public final int first;
public final int second;
public Pair(int first, int second) {
this.first = first;
this.second = second;
}
}
public class ExampleUnitTest {
@Test public void gapSize() throws Exception {
GapAwareList gaps = fillGaps();
gaps.put(0, 2);
gaps.put(0, 1);
gaps.put(3, 4);
gaps.put(6, 8);
List<Pair<Integer, Integer>> pairs = gaps.getPairs();
assertEquals(3, pairs.size());
}
@Test public void gapFirst() throws Exception {
GapAwareList gaps = fillGaps();
gaps.put(0, 2);
gaps.put(0, 1);
gaps.put(3, 4);
gaps.put(6, 8);
List<Pair<Integer, Integer>> pairs = gaps.getPairs();
assertTrue(pairs.get(0).first == 0);
assertTrue(pairs.get(0).second == 4);
}
@Test public void gapSecond() throws Exception {
GapAwareList gaps = fillGaps();
List<Pair<Integer, Integer>> pairs = gaps.getPairs();
assertTrue(pairs.get(1).first == 6);
assertTrue(pairs.get(1).second == 8);
}
private GapAwareList fillGaps() {
GapAwareList gaps = new GapAwareList();
//add (0,2),(0,1),(3,4),(6,8)
gaps.put(0, 2);
gaps.put(3, 4);
gaps.put(0, 1);
gaps.put(6, 8);
gaps.put(13,11);
gaps.put(13, 13);
gaps.put(13, 14);
return gaps;
}
@Test public void checkGaps(){
GapAwareList gaps = fillGaps();
assertFalse(gaps.haveGap(0,4));
assertFalse(gaps.haveGap(6, 8));
assertFalse(gaps.haveGap(6, 7));
assertTrue(gaps.haveGap(4, 6));
}
}
【问题讨论】:
-
JAVA 泛型不支持原语。如果你想这样,你可以创建一个显式数组。
-
您是在要求一个不允许间隙的列表实现,还是关于泛型?
-
@TimBiegeleisen 关于泛型。例如 HashMap 与 android SparseArray
-
@PriyanshGoel 是的,我知道这一点,请查看我的主题的编辑
-
您是否考虑过创建一个类,例如
Range保存整数并有List<Range>?
标签: java