Reputation: 13616
I have this class:
import java.util.Iterator;
import java.util.HashMap;
import java.util.Map;
public class Polynomial<T> implements Iterable<T> {
Map<Integer, Object> polynomial;
public Polynomial(){
polynomial = new HashMap<Integer, Object>();
}
public Polynomial(int numberOfMembers){
polynomial = new HashMap<Integer, Object>(numberOfMembers);
}
public void addElm(int power, int coefficient){
if (power < 0) {
power = Math.abs(power);
throw new RuntimeException("ERROR: The power must be an absolute number, converting to absolute");
}
for (Map.Entry m : polynomial.entrySet()) {
if ((Integer) m.getKey() == power){
polynomial.put(power,m.getValue());
}
}
}
@Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return (Iterator<T>) new Object;
}
}
And here is part of main function:
Polynomial<Integer> p1=new Polynomial<Integer>();
for (Integer r : p1)
System.out.println(r.toString());
As you can see above I need to make foreach on Polynomial class, that's why Polynomial implement Iterable interface. But my problem that I don't know how to implement iterator() method. How can I do that?
Upvotes: 0
Views: 549
Reputation: 271750
Your code is very confusing. What is T
? Why is T
not used in the class? What is the coefficient
parameter used for? What are you trying to do?
My best guess is that T
is the type of coefficient of the polynomial, and you are trying to return an iterator that iterates through the coefficients.
I rewrote your code like this:
public class Polynomial<T> implements Iterable<T> {
Map<Integer, T> polynomial;
public Polynomial(){
polynomial = new HashMap<Integer, T>();
}
public Polynomial(int numberOfMembers){
polynomial = new HashMap<Integer, T>(numberOfMembers);
}
public void addElm(int power, T coefficient){
if (power < 0) {
throw new RuntimeException("ERROR: The power must be an absolute number");
}
polynomial.put(power,coefficient);
}
@Override
public Iterator<T> iterator() {
return polynomial.values().iterator();
}
}
Upvotes: 3