簡體   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