gpt4 book ai didi

java - 具有初始值的 Class 实例的静态数组列表

转载 作者:行者123 更新时间:2023-11-29 06:51:39 24 4
gpt4 key购买 nike

我用一个静态数组列表创建了一个 Coin 类,它存储了创建的类的每个实例,但是我需要用一个初始实例启动该列表,而且我还没有想出如何在不添加它两次的情况下做到这一点(因为冗余代码),有什么建议吗?

public class Coin {
private static ArrayList<String> coinNames = new ArrayList<>();
private static ArrayList<String> coinAbbreviations = new ArrayList<>(Arrays.asList("CLP"));
private static ArrayList<Coin> coins =
new ArrayList<>(Arrays.asList(new Coin("Pesos chilenos", "CLP", 1f, "CLP")));
private static HashMap<String,Float> exchangeRates;
private String coinName;
private String coinAbbreviation;
private Float coinValue;
private String unit;


public Coin(String coinName, String coinAbbreviation, Float coinValue, String unit) {
assert !coinAbbreviations.contains(coinAbbreviation) : "Coin abbreviation already used";
assert coinAbbreviations.contains(unit) : "Coin unit non existent.";
assert !coinNames.contains(coinName) : "Coin name already used.";
this.coinName = coinName;
this.coinAbbreviation = coinAbbreviation;
this.coinValue = coinValue;
this.unit = unit;

coins.add(this);
}
}

最佳答案

如果您坚持使用可变静态变量——这样做通常根本不是一个好主意——您可以这样做

private static ArrayList<Coin> coins =
new ArrayList<>();

static {
new Coin("Pesos chilenos", "CLP", 1f, "CLP");
}

...立即将元素添加到列表中。

关于java - 具有初始值的 Class 实例的静态数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46306504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com