2013-03-21 313 views
0
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返回一个对象值,而不是LigneFacture价值,因此他要我把它投到LigneFacture,为什么呢?我在LigneFacture的列表中定义了我的迭代器。

回答

12

你使用的原料类型在这里:

Iterator iter_lignesFact = lignesFac.iterator(); 

您想使用的通用的形式:

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

你已经使用了原始类型,但你可避免的麻烦完全打字,和大量的代码,通过使用foreach循环:

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

使用foreach循环是,如果迭代一个非常整洁的方式。请注意,虽然整个迭代使用这种类型的循环,但您不得更改集合。具体来说,没有相应的iterator.remove()可用。但是,如果您的循环中不需要这种操作,则foreach是首选语法。

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