2013-03-21 136 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. 
} 
相關問題