如何使用foreach使类可迭代?

时间:2017-07-01 16:20:33

标签: java

我有这堂课:

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;
    }

}

这是主要功能的一部分:

 Polynomial<Integer> p1=new Polynomial<Integer>();
 for (Integer r : p1)
 System.out.println(r.toString());

正如您在上面所看到的,我需要在Polynomial类上进行foreach,这就是Polynomial实现Iterable接口的原因。但我的问题是我不知道如何实现iterator()方法。我怎么能这样做?

1 个答案:

答案 0 :(得分:3)

您的代码非常混乱。什么是T?为什么T没有在课堂上使用? coefficient参数用于什么?你想做什么?

我最好的猜测是T是多项式的系数类型,并且您试图返回迭代系数的迭代器。

我重写了这样的代码:

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();
    }

}