2012-05-08 88 views
1

假設我們只有一個簡單的對象Person,它具有用於標識它的int ID。我如何爲每個Person的新實例賦予新的ID值(+1),但是在該Person類的構造函數中? (我用這個沒有DB)如何在創建對象時在構造函數中自動分配變量

+1

@木瀆-S的回答是線程安全的,而其他所有的答案(這是確切的重複,包括我的答案,儘管我的第一)不是。 –

回答

9

使用靜態AtomicInteger

final class Foo { 
    private static final AtomicInteger seed = new AtomicInteger(); 
    private final int id; 

    public Foo() { 
    this.id = seed.incrementAndGet(); 
    } 
} 

在這裏看到更多的信息:https://stackoverflow.com/a/4818753/17713

1

使用靜態變量;靜態變量不會綁定到類實例,而是直接綁定到類。

實施例(在C#):

public class Person{ 
    public static int Increment = 1; 

    public int ID; 
    public Person(){ 
     this.ID = Increment; 
     Increment++; 
    } 
} 

這樣,所有的類實例將具有唯一的ID-S(增加1)。

編輯:這種方法不是線程安全的,請參閱@Mudu的答案。

+1

除了不是線程安全的,也不是具有公共變量的好主意,也不是遵循Java命名約定。 –

+1

請記住,這不是線程安全的,但只要不使用多線程就沒有問題。 –

+1

該解決方案沒有考慮到'Person'構造函數的線程調用。 –

1

你應該使用類似這是共享accros的所有實例

public class YourClass { 
    private static int generalIdCount = 0; 
    private int id; 

    public YourClass() { 
     this.id = generalIdCount; 
     generalIdCount++; 
    } 
} 
1

使用靜態計數場Person

class Person { 
    private static int nextId = 1; 
    private final int id; 

    Person() { 
     id = nextId++; 
    } 
} 
1

您可以爲當前計數器值的靜態變量,創建時賦值給該ID ...

public class Person { 

    // same across all instances of this class 
    static int currentCounter = 0; 

    // only for this instance 
    int personId; 

    public Person(){ 
     personId = currentCounter; 
     currentCounter++; 
    } 
} 
+1

與Luka的建議一樣,這不是線程安全的。 –

+1

是的。我認爲它取決於作者選擇最適合其上下文的答案,儘管像@Mudu這樣的線程安全答案將允許所有上下文無關。感謝您的反饋意見。 – wattostudios

相關問題