如何在构造函数内部初始化一个列表?

huangapple go评论78阅读模式
英文:

How to initialize a list inside a constructor?

问题

我有一个任务,需要在构造类内部初始化一个列表,但我不确定如何为主类中的参数进行赋值。

以下是我目前拥有的代码。

public CoinSorter(String currency, int maxCoinIn, int minCoinIn, List<Integer> coinList) {
    this.currency = currency;
    this.maxCoinIn = maxCoinIn;
    this.minCoinIn = minCoinIn;
    coinList = new ArrayList<Integer>();
    coinList.add(10);
    coinList.add(20);
    coinList.add(50);
    coinList.add(100);
    coinList.add(200);
}

主类代码如下:

CoinSorter cs = new CoinSorter("£", 10000, 0);

任何帮助将不胜感激!

英文:

I have an assignment where I need to initialize a list inside a constructor class, however I am not sure how to put the parameters in for the Main class.

This is the code that I have so far.

public CoinSorter(String currency, int maxCoinIn, int minCoinIn, List&lt;Integer&gt; coinList) {
this.currency = currency;
this.maxCoinIn = maxCoinIn;
this.minCoinIn = minCoinIn;
coinList = new ArrayList&lt;Integer&gt;();
coinList.add(10);
coinList.add(20);
coinList.add(50);
coinList.add(100);
coinList.add(200);}

and the main class code is

CoinSorter cs = new CoinSorter(&quot;&#163;&quot;, 10000, 0);

Any help would be appreciated!

答案1

得分: 0

public class Main {
    public static void main(String[] args) {
        CoinSorter cs = new CoinSorter("£", 10000, 0);
    }
}
public class CoinSorter {
    public String currency;
    public int maxCoinIn, minCoinIn;
    public List<Integer> coinList = new ArrayList<Integer>();

    public CoinSorter(String currency, int maxCoinIn, int minCoinIn) {
        this.currency = currency;
        this.maxCoinIn = maxCoinIn;
        this.minCoinIn = minCoinIn;

        this.coinList.addAll(Arrays.asList(10, 20, 50, 100, 200));
    }
}
英文:
public class Main {
    public static void main(String[] args) {
        CoinSorter cs = new CoinSorter(&quot;&#163;&quot;, 10000, 0);
    }
}
public class CoinSorter {
    public String currency;
    public int maxCoinIn, int minCoinIn;
    public List&lt;Integer&gt; coinList = new ArrayList&lt;Integer&gt;();

    public CoinSorter(String currency, int maxCoinIn, int minCoinIn) {
        this.currency = currency;
        this.maxCoinIn = maxCoinIn;
        this.minCoinIn = minCoinIn;

        this.coinList.addAll(Arrays.asList(10, 20, 50, 100, 200));
    }
}

huangapple
  • 本文由 发表于 2020年10月1日 09:50:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/64148022.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定