[英]A reference to primitive type in Java (How to force a primitive data to remain boxed)
[英]Custom type that acts like boxed primitive in Java
我想创建类似于Integer
或Double
的自定义类型。 以免说我有多级可导航 map:
// [UserLevel: [UserBalance: Multiplier]]
NavigableMap<Integer, NavigableMap<Double, Double>> multiplierByBalanceAndLevel
如果您不查看评论,它绝对不可读。 而且当我使用这样的Map
时,我也应该 go 到声明和检查评论。 这绝对很烦人,我想要类似的东西:
NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> multiplierByBalanceAndLevel
例如在 scala 中可以使用:
type UserLevel = Int
是否有可能以某种方式在 java 中实现? 也许有一些用于此类目的的库?
PS我可以用lombok帮助编写自定义实现
import java.util.NavigableMap;
import com.google.common.collect.ImmutableSortedMap;
import lombok.Value;
import lombok.experimental.Delegate;
public class TestExample {
@Value
static class UserLevel extends Number implements Comparable<UserLevel> {
@Delegate
Integer userLevel;
public int compareTo(UserLevel another) {
return this.userLevel.compareTo(another.getUserLevel());
}
}
@Value
static class UserBalance extends Number implements Comparable<UserBalance> {
@Delegate
Double userBalance;
public int compareTo(UserBalance another) {
return this.userBalance.compareTo(another.getUserBalance());
}
}
@Value
static class Multiplier extends Number implements Comparable<Multiplier> {
@Delegate
Double multiplier;
public int compareTo(Multiplier another) {
return this.multiplier.compareTo(another.getMultiplier());
}
}
public static void main(String[] args) {
double originalAmount = 10;
NavigableMap<UserLevel, NavigableMap<UserBalance, Multiplier>> multiplierByBalanceAndLevel =
ImmutableSortedMap.of(new UserLevel(1),
ImmutableSortedMap.of(new UserBalance(2.0), new Multiplier(3.0)));
Multiplier multiplier = multiplierByBalanceAndLevel
.floorEntry(new UserLevel(13)).getValue()
.ceilingEntry(new UserBalance(1.8)).getValue();
double amount = originalAmount * multiplier.getMultiplier();
}
}
但是包装类的使用看起来很丑陋并且产生了很多样板代码,因为它们不像自动装箱的那样
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.