2014-10-20 120 views
-1

所以我有一個類爲我創建一個數組列表,我需要通過構造函數在另一個類中訪問它,但我不知道要將什麼放入構造函數,因爲我的所有該類中的方法僅用於操縱該列表。即時獲取空指針異常或超出界限異常。我試圖把構造函數留空,但是這似乎有幫助。提前致謝。我會告訴你代碼,但我的教授對學術上的不誠實行爲非常嚴格,所以我不能對不起,如果這使得它很難。使用構造函數從另一個類訪問arraylist屬性

+0

不幸的是,它並沒有讓它變得困難;相反,它使*完全不可能*來幫助你。你至少可以嘗試以一種可以讓別人來幫助你的方式勾勒出問題。 – Gian 2014-10-20 22:20:00

+0

如果你不打算展示你曾經試過的,因爲你害怕教授會反對,你沒有一個很好的老師。另一方面,如果你真的希望自己解決這個問題,你不應該在這裏問。我們甚至可以提供答案? – 2014-10-20 22:20:08

回答

0

您在混淆主要問題和潛在解決方案。

主要問題:

I have a class ArrayListOwnerClass with an enclosed arraylist property or field. 
How should another class ArrayListFriendClass access that property. 

潛在的解決方案:

Should I pass the arraylist from ArrayListOwnerClass to ArrayListFriendClass, 
in the ArrayListFriendClass constructor ? 

這取決於第二類ArrayList中做什麼。

不是通過構造函數傳遞列表,而是添加函數來讀取或更改隱藏的內部數組列表的元素。

注意:您沒有指定編程語言。我將使用C#,altought Java,C++或類似的O.O.P.可以使用,而不是。

public class ArrayListOwnerClass 
{ 
    protected int F_Length; 
    protected ArrayList F_List; 

    public ArrayListOwnerClass(int ALength) 
    { 
    this.F_Length = ALength; 
    this.F_List = new ArrayList(ALength); 
    // ... 
    } // ArrayListOwnerClass(...) 

    public int Length() 
    { 
    return this.F_Length; 
    } // int Length(...) 

    public object getAt(int AIndex) 
    { 
    return this.F_List[AIndex]; 
    } // object getAt(...) 

    public void setAt(int AIndex, object AValue) 
    { 
    this.F_List[AIndex] = AValue; 
    } // void setAt(...) 

    public void DoOtherStuff() 
    { 
    // ... 
    } // void DoOtherStuff(...) 

    // ... 

} // class ArrayListOwnerClass 

public class ArrayListFriendClass 
{ 
    public void UseArrayList(ArrayListOwnerClass AListOwner) 
    { 
    bool CanContinue = 
     (AListOwner != null) && (AListOwner.Length() > 0); 
    if (CanContinue) 
    { 
     int AItem = AListOwner.getAt(5); 
     DoSomethingWith(Item); 
    } // if (CanContinue) 
    } // void UseArrayList(...) 

    public void AlsoDoesOtherStuff() 
    { 
    // ... 
    } // void AlsoDoesOtherStuff(...) 

    // ... 

} // class ArrayListFriendClass 

請注意,我可以使用索引屬性。

+0

謝謝你,我知道我的問題在措辭中含糊不清,但你的回答幫助我實現了多項應該允許我實現它的事情。 – Joeg332 2014-10-20 22:39:20

相關問題