English 中文(简体)
如果其构造中的某一个类别含有一个内层和一个阵列,那么如何在另一个类别中使用阵列?
原标题:if a class in its constructor contains an int,, and an array.. how can i use the array in another class.?
  • 时间:2010-11-12 21:23:40
  •  标签:
  • java
class C()
{
  num =4;
  int[] a = new int[5];
}

如果是,

C c1 = new C();

如何使用阵列?

最佳回答

通常建议不允许直接接触不同类别变量。 你们应该做的是:

public class C
{
   private int num = 4;
   private int[] a = new int[5];

   public int[] geta()
   {
       int[] arr = new int[a.length];
       System.arraycopy(a, arr, 0, a.length)
       return arr;
   }
}

public class Foo
{
   .
   .
   .
   C c = new C();
   int[] nums = c.geta();
}

该员额应有助于你了解更好的接收器和设计师。

Edit: 感谢评论家。

问题回答

向贵阶层提供进出(优)方法,并使之成为阵列的防御拷贝。

public int[] getA(){
    return Arrays.copyOf(a, a.length);
}

现在,其他类别可以做c.getA(),以获得阵列的副本(我们保护原阵列不受改动)。

假设你使用同一包裹,那么就在一面 in子上。 否则,你必须使C.a外地公之于众。

The easy way: Make it public.

The hard way: (and more professional) Make it private and provide a public property.

C c1 = new C();
c1.a[0] = 3;
// So on...

解释范围:没有进入平级区是一揽子准入。 违约准入意味着没有使用液化剂(公共、私人、)。

For more info: 控制级成员出入

<>A>。

c1.a

只有在属于同一等级的班级。

如你在“当地人”中定义的,它不能由任何其他人担任,甚至也不能由同一人行使另一个职能。 页: 1

public class C
{
  public int[] a;
  public int num;

  public C()
  {
    a=new int[5];
    num=42;
  }
}

然后,在其他地方,你可以写:

C c=new C();
if (c.num==37) ... etc ...

可以说,正如其他一些人指出的那样,你可能想要获得和制造,而不是公开变数。 我在座的公众人物和私人会员的相对优待中获胜。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签