我想将信息存储在缓存在内存中的 java 集合中。
我有下表
少于 $1 -(存储一些数据)
1 到 115,000 美元 -(存储一些不同的数据)
115,001 美元到 345,000 美元 -(存储一些不同的数据)
$345,001 到 580,000 -(存储一些不同的数据)
580,001 美元或更多 - (存储一些不同的数据)
我想将一定数量的钱传递给一个函数。然后我需要确定传入的货币属于哪个货币范围,以便我可以检索它的数据。例如传入了 127,000 美元。我需要使用上表中第三行的数据,因为 127,000 介于 115,000 美元和 345,000 美元之间。
我真的很感激任何关于如何最好地设计它的建议。
提前致谢 道格
最佳答案
这是一个基本的工作示例。当然,您可能想要使用 MAX_VALUE 和 MIN_VALUE 之外的其他东西作为外边界,并且您可能想要 float 而不是整数。完整的实现可能会将 CurrencyRange 作为接口(interface),您可以在其中针对“少于 1 美元”和“超过 580,000 美元”的情况使用不同的实现:
private static final List<CurrencyRange> ranges = Arrays.asList(
new CurrencyRange(Integer.MIN_VALUE, 0, "some data"),
new CurrencyRange(1, 115000, "some data"),
new CurrencyRange(115001, 345000, "some data"),
new CurrencyRange(345001, 580000, "some data"),
new CurrencyRange(580001, Integer.MAX_VALUE, "some data")
);
public String determineDataByAmount(int amount) {
for (CurrencyRange range : ranges) {
if (range.contains(amount)) {
return range.getData();
}
}
throw new IllegalStateException(
"No suitable range found for amount: " + amount);
}
class CurrencyRange {
private int lowerLimit;
private int upperLimit;
private String data;
public CurrencyRange(int lowerLimit, int upperLimit, String data) {
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
this.data = data;
}
public boolean contains(int amount) {
return amount >= lowerLimit && amount <= upperLimit;
}
public String getData() {
return data;
}
}
关于Java 集合使用货币范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6671129/