将Collection <user defined =“”class =“”>作为参数传递给java

时间:2017-01-02 05:32:42

标签: 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;
   } 
}

1 个答案:

答案 0 :(得分:0)

你想在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