2014-04-25 41 views
0

我一直在玩數組一段時間,這個問題一直困擾着我。初始化一個數組中的對象

我創建了一個用戶定義的對象,並將其聲明爲一個像這樣的數組:`Property regesteredAssets [] = new Property [200];

這是我的構造函數:`

public Property(String newPropertyName,String newPropertyAddress,String newPropertyType, String newPropertyDescription) 
    { 

    propertyName[arraySequence] = newPropertyName; 
    propertyFullAddress[arraySequence] = newPropertyAddress; 
    propertyType[arraySequence] = newPropertyType; 
    propertyDescription[arraySequence] = newPropertyDescription; 

     arraySequence++; 



} 

我想根據我的願望,初始化每個數組regesteredAsssets[]。我該怎麼做? 我是否也必須在Property類的屬性中使用數組?

+0

這只是語義,但我更喜歡聲明數組了他們的類型。 'Property [] registeredAssets;'而不是'Property registeredAssets [];'。更容易找到陣列和單個物體。 – indivisible

回答

0

你不需要你的屬性是數組,除非特定的資產有多個東西。在這種情況下,我不認爲它確實如此。您可以大大簡化你的代碼如下:

public class Property { 
    private String name, address, type, description; 

    public Property(String name, String address, String type, String description) { 
     this.name = name; 
     this.address = address; 
     this.type = type; 
     this.description = description; 
    } 

    public static void main(String[] args) { 
     Property[] registeredAssets = new Property[200]; 

     registeredAssets[0] = new Property("Joe Bloggs", "555 Fake St.", "IMPORTANT", "Lorem Ipsum Dolor"); 
     // etc. 
    } 
} 
+0

這有助於很多!謝謝! – user3519322

0

如果您有類型屬性的數組,你可以設置每個使用下面的代碼中的元素組成:

regesteredAssets[0] = new Property(enterYourParametersHere); 

我假定你的財產構造函數中的字段是單一領域,因此你不需要使用數組符號field[index] = value來設置它們,事實上,如果Property類具有我認爲的一致性,那麼這會產生編譯錯誤。

如果你想建立多個條目數組中,你可以執行一個循環中的初始化步驟,對陣列的如下的指標提供循環索引:

for(int i = 0; i < 10; i++) 
{ 
    regesteredAssets[i] = new Property(enterYourParametersHere); 
} 

我希望這有助於...

+0

謝謝!所以,每次我將一個新的參數傳遞給一個新的regesteredAsset [i];這些參數是否被分配給該特定對象? – user3519322

+0

是的,應該通過構造函數提供參數,並且每次命中'regesteredAsset [i]'時,數組中索引爲'i'的Property實例將具有這些參數,如構造函數代碼所示。 –