我在访问另一个类中的arraylist
元素时遇到了一个问题。我有2个班级:A班和B班。
class A {
private ArrayList<String> temp=new ArrayList<String>();
temp.add("abc");
temp.add("XYZ");
public ArrayList<String> getTemp() {
return this.temp;
}
}
public class B
{
private A a=null;
public b(A aa)
{
this.a = aa;
}
System.out.printLn(a.getTemp.size());//output is 2
System.out.printLn(a.getTemp.get(0));//null
}
为什么它给我null?请简要说明一下。
答案 0 :(得分:2)
以下是您要实现的目标的工作版本:
<强> A.java 强>
在A
课程中,您应该在构造函数中向ArrayList
添加元素:
public class A {
private ArrayList<String> temp=new ArrayList<String>();
public A() {
temp.add("abc");
temp.add("XYZ");
}
public ArrayList<String> getTemp() {
return this.temp;
}
}
<强> B.java 强>
构造函数名称应与该类匹配:
public class B {
private A a=null;
public B(A aa)
{
this.a = aa;
}
}
<强> App.java 强>
public class App {
public static void main(String[] args) {
A a = new A();
System.out.println(a.getTemp().size());
System.out.println(a.getTemp().get(0));
}
}
<强>输出:强>
2
abc
答案 1 :(得分:1)
您当前的代码甚至无法编译。
此外,我可以保证100%,如果通过某种魔术,你的代码编译第一个printLn
的输出绝不会2
。它将是null
。 `
答案 2 :(得分:1)
**First Of All Your Code Is Not Impossible to run**
You Can't assign value to instance variable directly in side of class without constructor or method so your modified class A must be like
**A.java**
class A {
private ArrayList<String> temp=new ArrayList<String>();
public A()
{
temp.add("abc");
temp.add("XYZ");
}
public ArrayList<String> getTemp()
{
return this.temp;
}
}
OR Like
class A {
private ArrayList<String> temp=new ArrayList<String>();
public A()
{
initialize();
}
public void initialize()
{
temp.add("abc");
temp.add("XYZ");
}
public ArrayList<String> getTemp()
{
return this.temp;
}
}
And Then As per Above Your Class B will Be
**B.java**
class B
{
private A a=null;
public B(A aa)
{
this.a = aa;
}
}
And Then you have to go for main method like
**Temp.java**
public class Temp {
public static void main(String... args)
{
A a = new A();
B b = new B(a);
System.out.println(a.getTemp().size());//output is 2
System.out.println(a.getTemp().get(0));//abc
}
}