简体   繁体   中英

adding objects to linkedlist/ arraylist in java

I created a storage class and use to as the data type for my arraylist/Linked list.

private LinkedList bid_history;

I have initialised this in my constructure as

bid_history=new LinkedList <Bid_History> ();

I add new items to the list using add as illustrated below

bid_history.add(new Bid_History(bid_count,unit_price,bid_success));

After 'n' iterations I checked the contents of the list and found out that the list has 'n' elements but they were the same. ie the last element i added occupied the entire list. It is as if i added a reference variable to the list?

Any idea where I might have made a mistake? I also used an arraylist, the same problem. I am guessing I did something wrong with access specifiers. but I am out of ideas.....

----Added ------- I use a recursive 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();
        }
}

the printing code is as follows

int count=0,size;
size=bid_history.size();
while(count<size)
System.out.println(((Bid_History)bid_history.get(count++)).getBid_amount());

Another possibility is that BidHistory(count, price, success) is not doing the right job and not setting the right fields. I don't want to guess, but it might be that instead of having fields in BidHistory you are using static count/price/success fields in the class.

The constructor should look like ("this." is important):

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

The only explanation to your problem I can think of is that the values of bid_count , unit_price and bid_success are not changed in each iteration.

I propose the following changes to make the code easier:

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

The final makes sure that the list cannot be replaced by another list. The generic prevents you from accidentally adding incompatible objects to the list. It also makes looping over the list easier. The class Lists from Google Guava keeps the code short, since you don't have to mention the generic datatype twice.

All the fields in the BidHistory class should be made final , too, so you cannot change them later. Since this is about history, you should not be able to change the facts later anyway.

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

I chose to print the defaultHashCode of each bid to check whether the objects are the same or not. For non-same objects the defaultHashCode is very likely to be different, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM