2013-11-04 5 views
0

클래스를 프로그래밍하여 새 객체가 생성 될 때마다 그 객체에 새 생성 된 코드가 생기도록하지만 그 값을 전달하지 않는 것이 트릭입니다. 생성자에 대한 인수 대략 나는 다음과 같습니다클래스 내에서 변수 값이 자동으로 생성됩니다.

다음
public class Article{ 
    private int cod; 
    private String name; 
    public Article(String name){ 
     this.name=name: 
    } 
} 

I가이 기사 클래스를 호출 할 수있는 송장라는 클래스 :

public class Invoice{ 
    ArrayList<Article> detailList; 
    public add(Article a){ 
      detailsList.add(a); 
    } 
    public ArrayList<Article> getArticleList(){ 
      return detailList; 
    } 
} 

그래서 난 때마다 내가 메인 클래스의 일부 기사를 만드는 것이 원하는 그리고 코드가 자동으로 생성 한 위해 Invoie 클래스들을 추가 : 내가 사용 시도

main class 

    ArrayList<Article> temp; 
    Article a1=new Article(....) 
    Article a2=new Article(....) 
    Article a3=new Article(....) 
    Invoice inv; 
    inv.add(a1) 
    inv.add(a2) 
    inv.add(a3) 
    //for example I want the first element to get a code of 10, the next as 20 and so on 
    temp=inv.getArticleList(); 
     for (int i=0;i<temp.size();i++){ 
      System.out.println(temp.get(i).getCod()); 
     } 

:

private static int cod 기사 클래스

다음에 +10을 추가 할 때마다 add 메소드를 호출하지만 주 클래스의 목록에서 결과를 인쇄 할 때 최종 생성 코드 만 인쇄됩니다. 어떻게 해결할 수 있습니까?

감사

+0

정적 변수가 무엇인지 읽어보십시오. 지금처럼 거의 사용할 수 있지만 동기화 된 블록 내에서 또는 AtomicInteger를 사용하여 인스턴스 변수에 정적 변수를 할당해야합니다. –

+0

코드가 계산되지 않고 코드를 추가하거나 빼기를 원하는 곳이 명확하지 않습니다. –

답변

3
당신은 속성, 인스턴스 레벨에서 하나 static와 하나가 필요합니다

: 위의 사용

public class Article { 

    private int cod; 
    private String name; 
    private static int counter = 10; 

    public Article(String name) { 
     this.name = name; 
     this.cod = counter; 
     counter += 10; 
    } 

} 

를, 각 기사는 10에서 시작하여 열을 증가, 다른 코드가됩니다 단위 때마다.

public class Invoice { 
    ArrayList<Article> detailList = new ArrayList<Article>(); 
    public void add(Article a) { 
     detailList.add(a); 
    } 
    public ArrayList<Article> getArticleList(){ 
      return detailList; 
    } 
} 

지금이 예상대로 작동 : 내가 게시 된 코드에서 몇 가지 오류를 수정이 Invoice 클래스를 사용하여 테스트

그것은 콘솔에 인쇄
Invoice inv = new Invoice(); 
inv.add(a1); 
inv.add(a2); 
inv.add(a3); 
ArrayList<Article> temp = inv.getArticleList(); 
for (int i=0;i<temp.size();i++){ 
    System.out.println(temp.get(i).getCod()); 
} 

:

10 
20 
30 
+0

다중 스레드 환경에있는 경우가 아니면 다음과 같은 정적 카운터를 사용하여 생성 된 "cod"가 인스턴스간에 고유하다는 것을 보장하지는 못합니다. –

+0

thansk @oscar하지만 목록에서 결과를 인쇄 할 때 결과가 올바르게 표시되지 않습니다. 두 코드 만 가져오고 세 번째 코드는 중복됩니다. – Little

+0

@Giodude OP는 프로그래밍 방법을 배우고 있습니다. 관심이 유효합니다 ("단일 스레드 환경"을 의미한다고 생각합니다.)하지만 멀티 스레딩 문제는 다음과 같습니다. 지금 영업 이익에 대한 우려는 거의 없다. –

1

다음은 Oscar 코드의 스레드 안전 버전입니다.

import java.util.concurrent.atomic.AtomicInteger; 

public class Article { 
    private int cod; 
    private String name; 
    private final static AtomicInteger counter = new AtomicInteger(10); 

    public Article(String name) { 
    this.name = name; 
    this.cod = counter.getAndAdd(10); 
    } 
} 

AtomicInteger를 사용하면 여러 스레드에서 Article 인스턴스를 동시에 만들 수 있습니다. 일반 int를 사용하면 카운터의 "더티 (dirty)"읽기가 발생할 수 있으므로 Article의 인스턴스마다 카운터의 값이 달라집니다.

관련 문제