使用构造函数从另一个类访问arraylist属性
问题描述:
所以我有一个类为我创建一个数组列表,我需要通过构造函数在另一个类中访问它,但我不知道要将什么放入构造函数,因为我的所有该类中的方法仅用于操纵该列表。即时获取空指针异常或超出界限异常。我试图把构造函数留空,但是这似乎有帮助。提前致谢。我会告诉你代码,但我的教授对学术上的不诚实行为非常严格,所以我不能对不起,如果这使得它很难。使用构造函数从另一个类访问arraylist属性
答
您在混淆主要问题和潜在解决方案。
主要问题:
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
不幸的是,它并没有让它变得困难;相反,它使*完全不可能*来帮助你。你至少可以尝试以一种可以让别人来帮助你的方式勾勒出问题。 – Gian 2014-10-20 22:20:00
如果你不打算展示你曾经试过的,因为你害怕教授会反对,你没有一个很好的老师。另一方面,如果你真的希望自己解决这个问题,你不应该在这里问。我们甚至可以提供答案? – 2014-10-20 22:20:08