java [Java]我想写得更优雅
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java [Java]我想写得更优雅相关的知识,希望对你有一定的参考价值。
import java.util.HashMap;
public class NumberMap {
HashMap<String, Number> map = new HashMap<>();
public void put(String key, Number value) {
if (value instanceof Double
|| value instanceof Float
|| value instanceof Integer
|| value instanceof Long
|| value instanceof Short) {
map.put(key, value);
} else {
throw new RuntimeException("NumberMap does not support BigDecimal, BigInteger and Byte.");
}
}
public <T extends Number> T get1(String key, T defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return (T)ret;
}
}
public <T extends Number> T get2(String key, T defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else if (defaultValue.getClass().isInstance(ret)) {
return (T)ret;
} else if (defaultValue instanceof Double) {
return (T)((Double)ret.doubleValue());
} else if (defaultValue instanceof Float) {
return (T)((Float)ret.floatValue());
} else if (defaultValue instanceof Integer) {
return (T)((Integer)ret.intValue());
} else if (defaultValue instanceof Long) {
return (T)((Long)ret.longValue());
} else if (defaultValue instanceof Short) {
return (T)((Short)ret.shortValue());
} else {
throw new RuntimeException("defaultValue must be double|float|int|long|short.");
}
}
public double get3(String key, double defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return ret.doubleValue();
}
}
public float get3(String key, float defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return ret.floatValue();
}
}
public int get3(String key, int defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return ret.intValue();
}
}
public long get3(String key, long defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return ret.longValue();
}
}
public short get3(String key, short defaultValue) {
Number ret = map.get(key);
if (ret == null) {
return defaultValue;
} else {
return ret.shortValue();
}
}
public static void main(String[] args) {
NumberMap map = new NumberMap();
map.put("double", 1.0d);
map.put("int", 1);
// NG - java.lang.ClassCastException:
// java.lang.Integer cannot be cast to java.lang.Double
double doubleGet1 = map.get1("int", 1.0d);
// NG - java.lang.ClassCastException:
// java.lang.Double cannot be cast to java.lang.Integer
int intGet1 = map.get1("double", 1);
// OK
double doubleGet2 = map.get2("int", 1.0d);
// OK
int intGet2 = map.get2("double", 1);
// OK
double doubleGet3 = map.get3("int", 1.0d);
// OK
int intGet3 = map.get3("double", 1);
}
}
以上是关于java [Java]我想写得更优雅的主要内容,如果未能解决你的问题,请参考以下文章