在java中将对象添加到linkedlist / arraylist

时间:2011-07-03 08:26:44

标签: java arraylist linked-list

我创建了一个存储类,并将其用作我的arraylist / Linked列表的数据类型。

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,同样的问题。我猜我访问说明符做错了!但我没有想法......

----添加------- 我使用递归函数

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());

3 个答案:

答案 0 :(得分:5)

另一种可能性是BidHistory(计数,价格,成功)没有做正确的工作而没有设置正确的字段。我不想猜,但可能不是在BidHistory中有字段而是在类中使用静态计数/价格/成功字段。

构造函数应该看起来像(“this。”很重要):

public BidHistory(int count, float price, boolean success) {
    this.count = count;
    this.price = price;
    this.success = success;
}

答案 1 :(得分:0)

我能想到的问题的唯一解释是bid_countunit_pricebid_success的值在每次迭代中都不会更改。

答案 2 :(得分:0)

我建议进行以下更改以使代码更容易:

private final List<BidHistory> bidHistory = Lists.newLinkedList();

final确保列表不能被其他列表替换。通用程序可防止您意外地将不兼容的对象添加到列表中。它还使得在列表上循环更容易。来自Google Guava的班级Lists可以缩短代码,因为您不必两次提及通用数据类型。

BidHistory课程中的所有字段也应设为final,因此您以后无法更改这些字段。由于这是关于历史的,所以无论如何你都不应该改变事实。

private void printHistoryForDebugging() {
  for (BidHistory bid : bidHistory) {
    System.out.println(bid.getBidAmount() + " (hashCode " + System.defaultHashCode(bid) + ")");
  }
}

我选择打印每个出价的defaultHashCode来检查对象是否相同。对于不同的对象,defaultHashCode也很可能不同。