迭代器返回一个Object而不是所需的对象

时间:2013-03-21 22:58:12

标签: java object iterator

public class Facture {
private Client client = new Client();;
private float Paiement;
private float soustotal;
private float tps;
private float tvq;
private float ttc;
private List<LigneFacture> lignesFac = new ArrayList<LigneFacture>();

public Facture(){
    this.Paiement=0;
    this.soustotal=0;
    this.tps=0;
    this.tvq=0;
    this.ttc=0;

}
public Client getClient() {
    return client;
}

public void setClient(Client client) {
    this.client = client;
}

public float getPaiement() {
    return Paiement;
}

public void setPaiement(float Paiement) {
    this.Paiement = Paiement;
}

public float getSoustotal() {
    return soustotal;
}

public void setSoustotal(float soustotal) {
    this.soustotal = soustotal;
}

public float getTps() {
    return tps;
}

public void setTps(float tps) {
    this.tps = tps;
}

public float getTvq() {
    return tvq;
}

public void setTvq(float tvq) {
    this.tvq = tvq;
}

public float getTtc() {
    return ttc;
}

public void setTtc(float ttc) {
    this.ttc = ttc;
}

public List<LigneFacture> getLignesFac() {
    return lignesFac;
}
public void addLignesFacture(LigneFacture ligneFac){
    this.lignesFac.add(ligneFac);
    Iterator iter_lignesFact = lignesFac.iterator();

    while(iter_lignesFact.hasNext()){
       LigneFacture lignefac_cur =  iter_lignesFact.next();
    }
}

}

嗨我有这个类,问题出在最后一个方法中,Java告诉我iter_lignesFact返回一个Object值而不是LigneFacture值,因此他希望我把它转换为LigneFacture,为什么呢?我在LigneFacture列表中定义了我的迭代器。

3 个答案:

答案 0 :(得分:13)

你在这里使用了原始类型:

Iterator iter_lignesFact = lignesFac.iterator();

您想使用通用表单:

Iterator<LigneFacture> iter_lignesFact = lignesFac.iterator();

答案 1 :(得分:1)

您使用了原始类型,但是通过使用foreach循环可以避免完全输入和大量代码的麻烦:

for (LigneFacture lignefac_cur : lignesFac) {
    // do something with lignefac_cur
}

如果迭代,使用foreach循环是一种非常整洁的方法。请注意,尽管使用这种循环进行整个迭代,但您可能无法更改集合。具体而言,没有相当于iterator.remove()的可用内容。但是,如果在循环中不需要这种操作,则foreach是首选语法。

答案 2 :(得分:0)

并且,您根本不想使用Iterator。我们这个功能在做什么?

public void addLignesFacture(LigneFacture ligneFac){
    this.lignesFac.add(ligneFac);
    Iterator iter_lignesFact = lignesFac.iterator();

    while(iter_lignesFact.hasNext()){
       LigneFacture lignefac_cur =  iter_lignesFact.next();
    }
} 

首先,它将ligneFac添加到列表lignesFacligneFac现在是列表中的最后一个成员,除非出现奇怪的线程情况。然后,创建迭代器,并依次为每个成员设置lignefac_cur,停在最后一个成员ligneFac。那么,为什么不简单地将lignefac_cur设置为ligneFac?但是,你扔掉了lignefac_cur。我假设你缩短了你最初编写的方法。

public void addLignesFacture(LigneFacture ligneFac){
    this.lignesFac.add(ligneFac);

    LigneFacture lignefac_cur =  ligneFac;
    // Do things with lignefac_cur.
    // You might want to make it an instance variable instead,
    // or even to have a method currentLigne() that gets the last
    // member of the list. You might even want to use
    // Stack or Queue as being more expressive.
} 
相关问题