[英]Java - Object is not being set?
考慮下面的代碼,嘗試將Product
對象添加到productList
,它是類型Product[]
的數組。
public void addItem(Product product) {
for (Product p : productList) {
if (p != null){
p = product;
}
}
System.out.println(productList[0]); // This yields null.
}
就像注釋一樣,打印結果為null
。 為什么未設置產品?
更新:我已經在!= null
子句中運行了debug-printouts,對象和子句的其余部分都正常運行。
在for-each-loop中,變量p
是一個臨時變量, productList
的內容將分配給該臨時變量。 因此,您總是只分配臨時變量,而不是分配給列表中的項目。
您可能想要這樣:
for (int i = 0; i < productList.length; i++)
{
if (productList[i] == null)
{
productList[i] = product;
break;
}
}
如果沒有break
,則將product
分配給所有為null
項目(實際上最好使用boolean
s來處理循環中斷,但這也可行)
您不能使用for-each循環(也稱為“增強型” for循環)來設置數組變量,因為它在循環內部使用了temp變量。 您可以使用它來更改數組已保存的對象的狀態,因為temp變量將引用同一對象,但不能設置引用本身。 解決方案:使用標准的for循環。
根據Java語言規范§14.14.2 :
增強的for語句等效於以下形式的基本for語句:
for (I #i = Expression.iterator(); #i.hasNext(); ) { VariableModifiersopt TargetType Identifier = (TargetType) #i.next(); Statement }
因此,就您而言,寬松地:
for (int n; n < productList.length; ++n) {
Product p = productList[n];
if (p != null) {
p = product;
}
}
productList[0]
,為什么從未設置productList[0]
。 在該循環迭代的持續時間內設置了p
,但未設置productList[0]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.