I have a class SimpHisto
that takes in an array of generic type SL
, and returns the size and the count of a specific element of that array.
After I tried to run my code,
I get an error saying:
> Task :compileJava UP-TO-DATE
> Task :processResources UP-TO-DATE
> Task :classes UP-TO-DATE
> Task :compileTestJava
> Task :processTestResources NO-SOURCE
> Task :testClasses
> Task :test FAILED
No element at index
Can someone please explain what's wrong with my code and provide any explanations on solutions?
Thank you
CodePudding user response:
The error is in your Iterate
.
You throw that exception if (index <= items.length)
.
index
starts with 0 so this is always true
.
You only have to change to >=
As mentioned by 英語は苦手 your while
in getCount
does not call next
.
Since you iterate over the items directly I would prefer to remove the Iterator
at all.
And a Stream
may increase readability:
return (int) Stream.of(this.items)
.filter(dt -> dt == item)
.count();
EDIT: without Stream
-API you can iterate over your items
directly:
for (SL dt : this.items) {
if (dt == item) {
n ;
}
}
If you want to use the Iterator
you have to call next
while (L.hasNext()) {
SL dt = L.next();
if (dt == item) {
n ;
}
}
BTW: why assertEquals(3, elemCount);
? There are 4 elements