将 Collection<user defined class> 作为参数传递给 java 中 class 的构造函数

Passing a Collection<user defined class> as a parameter to the constructor of the class in java

在下面的代码片段中,如何使用 coll 从 class 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;
   } 
}

你想在你的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();

如果我没猜错,下面的代码可以做到。如果不是,请编辑您的问题并解释。

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);
        }
    }
}

现在我为 main() 建议的代码将打印:

Lion       114   1
Java         9  -1