2011-07-03 3 views
1

스토리지 클래스를 생성하여 내 arraylist/Linked list의 데이터 유형으로 사용했습니다.linkedlist/arraylist to java에 객체 추가

private LinkedList bid_history; 

내가

bid_history=new LinkedList <Bid_History>(); 

나의 constructure이를 초기화 한 나는 내용을 확인 'n'을 반복 한 후

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

아래 그림과 같이 추가 사용하여 목록에 새 항목을 추가 목록에 'n'개 요소가 있지만 모두 동일하다는 사실을 알게되었습니다. 즉, 추가 된 마지막 요소 i가 전체 목록을 차지했습니다. 마치 목록에 참조 변수를 추가 한 것입니까?

내가 실수했을 수도있는 아이디어가 있습니까? 나는 또한 같은 문제 인 arraylist를 사용했다. 액세스 지정자에 문제가 있다고 생각합니다! 하지만 난

가 ---- ------- 내가

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

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

인쇄 코드는 재귀 함수를 사용하여 추가 ..... 아이디어 중입니다

+3

표시된 코드에 문제가없는 것 같습니다. 귀하의 (편집 된) 루프 코드를 보여주십시오. 우리는 당신을 도울 더 많은 정보가 필요합니다. 또한, 그들이 모두 똑같은지 어떻게 알 수 있습니까? 그 코드도 보여주세요 – Bohemian

+0

연속적인 반복에서'bid_count, unit_price, bid_success'의 값을 변경하고 있습니까? –

+0

'bid_success'가 다른 함수에 의해 수정되었습니다. – Gan

답변

5

또 다른 가능성은 BidHistory (카운트, 가격, 성공)가 올바른 작업을 수행하지 않고 올바른 필드를 설정하지 않는다는 것입니다. 추측하고 싶지는 않지만 BidHistory에 필드가있는 대신 클래스의 정적 개수/가격/성공 필드를 사용하고있을 수 있습니다.

생성자가 같아야는 (".이"중요하다) : 나는 코드를 쉽게하기 위해 다음과 같이 변경을 제안

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

당신은 맞습니다. 나는 정적 변수를 사용하고 getters와 setters를 생성하기 위해 이클립스를 사용했으며 실제로 더 자세히 살펴 보지 않았다. – Gan

0

내가 생각할 수있는 유일한 문제는 각 반복에서 bid_count, unit_pricebid_success의 값이 변경되지 않는다는 것입니다.

0

:

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

final 확실하게 목록이 다른 목록으로 대체 할 수 없습니다. generic을 사용하면 실수로 호환되지 않는 객체를 목록에 추가하는 것을 방지 할 수 있습니다. 또한 목록에 대한 루핑이 쉬워집니다. Google 구아바의 클래스 Lists은 일반 데이터 유형을 두 번 언급 할 필요가 없으므로 코드를 짧게 유지합니다.

BidHistory 클래스의 모든 입력란은 final으로 만들어야 나중에 변경할 수 있습니다. 이것은 역사에 관한 것이므로 나중에 어쨌든 사실을 변경할 수 없어야합니다.

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

나는 객체가 동일하거나하지 여부를 확인하기 위해 각 입찰의 defaultHashCode를 인쇄하기로 결정했습니다. 동일하지 않은 객체의 경우 defaultHashCode도 매우 다를 수 있습니다.