[英]Passing a Collection<user defined class> as a parameter to the constructor of the class in java
In below code snippet, how can I access variables from class B using coll
? 在下面的代码片段中,如何使用coll
访问类B中的变量? I want to add data in coll
in A.main()
method and print all data using a loop. 我想在A.main()
方法的coll
中添加数据,并使用循环打印所有数据。
class A{
class B{
String str;
int i1;
int i2;
}
private Collection<B> coll;
public A(Collection<B> _coll){
coll = _coll;
}
}
What you want to do in your main()
, is it something like this? 您想要在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();
If I am guessing correctly, the code below can do it. 如果我猜对了,下面的代码可以做到。 If not, please edit your question and explain. 如果没有,请编辑您的问题并解释。
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);
}
}
}
Now the code I suggested for main()
will print: 现在,我为main()
建议的代码将打印:
Lion 114 1
Java 9 -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.