Created
January 10, 2012 02:08
-
-
Save adam-singer/1586382 to your computer and use it in GitHub Desktop.
Example of a possible extension of List to include a indexesOf method.
This file contains 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
class ListExtension { | |
/** | |
* Returns a [List] of indexes of the given [element], starting | |
* the search at index [startIndex] to [endIndex] (exclusive). | |
* Returns an empty [List] if [element] is not found. | |
*/ | |
static List<num> indexesOf(List list, Object element, int startIndex, int endIndex) { | |
List<num> n = new List<num>(); | |
if (startIndex >= list.length) { | |
return n; | |
} | |
if (startIndex < 0) { | |
startIndex = 0; | |
} | |
for (int i = startIndex; i < endIndex; i++) { | |
if (list[i] == element) { | |
n.add(i); | |
} | |
} | |
return n; | |
} | |
} |
This file contains 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
void main() { | |
void run() { | |
List<num> l = new List<num>(); | |
l.add(10); | |
l.add(20); | |
l.add(10); | |
l.add(30); | |
List<num> e = ListExtension.indexesOf(l, 10, 0, l.length); | |
Expect.equals(2, e.length); | |
Expect.equals(0, e[0]); | |
Expect.equals(2, e[1]); | |
} | |
run(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment