First of all, and in order for you to understand this question, i'm going to briefly explain my project:
I have a class named Pair, which basically creates the type
Pair<String,Double>
and has a getFirst() and getSecond() methods for returning the String and Double values respectively.
Then i have another class, named Package, which basically consists in a list of Pairs, and implements the Iterable interface, so i can iterate trough the list:
Package<Pair<String,Double>> package;
List <Pair<String,Double>> list;
What i want is to sum the doubles on each Pair, using the iterator().
The iterator is defined like this for the Package class:
public Iterator<E> iterator() {
return this.iterator();
}
I've tried two different approaches, which in both cases resulted in a:
Exception in thread "main" java.lang.StackOverflowError
at Package.iterator(Package.java:98)
Here's the first one:
public static double packageWeight(Package<Pair<String, Double>> package) {
double sum = 0;
Pair<String, Double> pair;
while (package.iterator().hasNext()) {
pair = package.iterator().next();
sum = sum + pair.getSecond();
}
return sum;
}
And the second one:
public static double packageWeight(Package<Pair<String, Double>> package) {
double sum = 0;
Pair<String, Double> pair;
Iterator<Pair<String,Double>> it = Package.iterator();
while (it.hasNext()) {
pair = it.next();
sum = sum + pair.getSecond();
}
return sum;
}
My question is: What am i doing wrong in order to get this error?
package, surely? It's a java keyword.Package.iterator()unless you make itstatic.Iterableinterface and use a for-each. That will be less error prone...