传递集合<;用户定义类>;作为java中类的构造函数的参数
在下面的代码片段中,如何使用传递集合<;用户定义类>;作为java中类的构造函数的参数,java,class,collections,constructor,private,Java,Class,Collections,Constructor,Private,在下面的代码片段中,如何使用coll访问B类变量? 我想在coll中的A.main()方法中添加数据,并使用循环打印所有数据 class A{ class B{ String str; int i1; int i2; } private Collection<B> coll; public A(Collection<B> _coll){ coll = _coll; } } A类{ B
coll
访问B类变量?
我想在coll
中的A.main()
方法中添加数据,并使用循环打印所有数据
class A{
class B{
String str;
int i1;
int i2;
}
private Collection<B> coll;
public A(Collection<B> _coll){
coll = _coll;
}
}
A类{
B类{
字符串str;
int i1;
int i2;
}
私人收藏馆;
公共A(集合)
coll=_coll;
}
}
您想在main()
中做什么,是这样的吗
Collection<A.B> newColl = Arrays.asList(new A.B("Lion", 114, 1), new A.B("Java", 9, -1));
A myAInstance = new A(newColl);
myAInstance.printAll();
main()方法属于何处?具体问题是什么?我看到您设计中的一个直接问题是,构造函数需要
Collection
作为输入,但您的内部类B
是包私有的。@TimBiegeleisen关键是构造函数是公共的。标题与此无关“在coll in main()方法中添加数据”。这真的是你的问题吗?你的main方法甚至在同一个包中吗?是的,这是我所期望的。很高兴听到这个。请随意接受左边勾号上的答案。更多关于此的信息,请访问
public class A {
public static class B {
String str;
int i1;
int i2;
public B(String str, int i1, int i2) {
this.str = str;
this.i1 = i1;
this.i2 = i2;
}
@Override
public String toString() {
return String.format("%-10s%4d%4d", str, i1, i2);
}
}
private Collection<B> coll;
// in most cases avoid underscore in names, especailly names in the public interface of a class
public A(Collection<B> coll) {
this.coll = coll;
// or may make a "defensive copy" so that later changes to the collection passed in doesn’t affect this instance
// this.coll = new ArrayList<>(coll);
}
public void printAll() {
// Requirements said "print all data using a loop", so do that
for (B bInstance : coll) {
System.out.println(bInstance);
// may also access variables from B, for instance like:
// System.out.println(bInstance.str + ' ' + bInstance.i1 + ' ' + bInstance.i2);
}
}
}
Lion 114 1
Java 9 -1