繁体   English   中英

通过收藏 <user defined class> 作为java中类的构造函数的参数

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

在下面的代码片段中,如何使用coll访问类B中的变量? 我想在A.main()方法的coll中添加数据,并使用循环打印所有数据。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM