[英]adding objects to linkedlist/ arraylist in java
我創建了一個存儲 class 並用作我的數組列表/鏈接列表的數據類型。
private LinkedList bid_history;
我已在我的結構中將其初始化為
bid_history=new LinkedList <Bid_History> ();
我使用 add 將新項目添加到列表中,如下圖所示
bid_history.add(new Bid_History(bid_count,unit_price,bid_success));
在“n”次迭代后,我檢查了列表的內容,發現列表有“n”個元素,但它們是相同的。 即我添加的最后一個元素占據了整個列表。 就好像我在列表中添加了一個引用變量?
知道我可能在哪里犯了錯誤嗎? 我還使用了 arraylist,同樣的問題。 我猜我在訪問說明符上做錯了什么。 但我沒有想法......
----添加-------我使用遞歸的function
bid()
{
int bid,quantity;
bid_success=false;
bid_count++;
System.out.println("Starting to bid, Bid ID:"+bid_count);
quantity=(int)(rated_power*duration/60);
if(bid_history.isEmpty())
{
unit_price=10;
}
else
{
unit_price++;
}
bid=unit_price*quantity;
//Sending the calculated bid
send_res(unit_price,quantity,500);
long startTimeMs = System.currentTimeMillis( );
System.out.println("Time:"+startTimeMs);
while(!(System.currentTimeMillis( )>(startTimeMs+2000)));
System.out.println("Time at end:"+System.currentTimeMillis( ));
bid_history.add(new Bid_History(bid_count,unit_price,bid_success));
if(bid_success!=true)
{
bid();
}
}
打印代碼如下
int count=0,size;
size=bid_history.size();
while(count<size)
System.out.println(((Bid_History)bid_history.get(count++)).getBid_amount());
另一種可能性是 BidHistory(count, price,success) 沒有做正確的工作並且沒有設置正確的字段。 我不想猜測,但可能是您在 class 中使用 static 計數/價格/成功字段,而不是 BidHistory 中的字段。
構造函數應該看起來像(“this.”很重要):
public BidHistory(int count, float price, boolean success) {
this.count = count;
this.price = price;
this.success = success;
}
我能想到的對您的問題的唯一解釋是bid_count
、 unit_price
和bid_success
的值在每次迭代中都不會改變。
我建議進行以下更改以使代碼更容易:
private final List<BidHistory> bidHistory = Lists.newLinkedList();
final
確保該列表不能被另一個列表替換。 泛型可防止您意外將不兼容的對象添加到列表中。 它還使循環列表更容易。 來自 Google Guava 的 class Lists
保持代碼簡短,因為您不必兩次提及通用數據類型。
BidHistory
class 中的所有字段也應設為final
,因此您以后無法更改它們。 由於這是關於歷史的,因此您以后無論如何都不能更改事實。
private void printHistoryForDebugging() {
for (BidHistory bid : bidHistory) {
System.out.println(bid.getBidAmount() + " (hashCode " + System.defaultHashCode(bid) + ")");
}
}
我選擇打印每個出價的defaultHashCode
以檢查對象是否相同。 對於不同的對象,defaultHashCode 也很可能不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.