SmartList - efficient indexOf / contains

This commit is contained in:
Vladimir Krivosheev
2016-12-09 13:57:29 +01:00
parent b30573026d
commit 7bd46db65d
2 changed files with 63 additions and 2 deletions
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -288,4 +288,41 @@ public class SmartList<E> extends AbstractList<E> implements RandomAccess {
myElem = Arrays.copyOf(array, mySize);
}
}
@Override
public int indexOf(Object o) {
if (mySize == 0) {
return -1;
}
else if (mySize == 1) {
if (o == null) {
return myElem == null ? 0 : -1;
}
else {
return o.equals(myElem) ? 0 : -1;
}
}
Object[] array = (Object[])myElem;
if (o == null) {
for (int i = 0; i < mySize; i++) {
if (array[i] == null) {
return i;
}
}
}
else {
for (int i = 0; i < mySize; i++) {
if (o.equals(array[i])) {
return i;
}
}
}
return -1;
}
@Override
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
}
@@ -39,7 +39,12 @@ public class SmartListTest {
List<Integer> l = new SmartList<>();
l.add(1);
assertThat(l).hasSize(1);
assertThat(l.get(0).intValue()).isEqualTo(1);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.indexOf(1)).isEqualTo(0);
assertThat(l.indexOf(2)).isEqualTo(-1);
assertThat(l.contains(1)).isTrue();
assertThat(l.contains(2)).isFalse();
}
@Test
@@ -50,6 +55,13 @@ public class SmartListTest {
assertThat(l).hasSize(2);
assertThat(l.get(0)).isEqualTo(1);
assertThat(l.get(1)).isEqualTo(2);
assertThat(l.indexOf(1)).isEqualTo(0);
assertThat(l.indexOf(2)).isEqualTo(1);
assertThat(l.contains(1)).isTrue();
assertThat(l.contains(2)).isTrue();
assertThat(l.indexOf(42)).isEqualTo(-1);
assertThat(l.contains(42)).isFalse();
}
@Test
@@ -257,4 +269,16 @@ public class SmartListTest {
assertThat(l.toArray(new Integer[4])).containsExactly(0, null, null, null);
assertThat(l.toArray()).containsExactly(0);
}
@Test
public void testNullIndexOf() {
List<Integer> l = new SmartList<>();
l.add(null);
l.add(null);
assertThat(l.indexOf(null)).isEqualTo(0);
assertThat(l.contains(null)).isTrue();
assertThat(l.indexOf(42)).isEqualTo(-1);
assertThat(l.contains(42)).isFalse();
}
}