我必须创建一个包装器类来保存任何原始数据类型.我创建了该类,该类可用于除布尔值以外的所有内容.这是我的代码:
byte a; // the byte in primitive
short b; // the short
int c, j; // int c is is int, j is the counter for Primitive to tell what dataType it is
long d; // the long
float e; //the float
double f; // the double
boolean g; // the boolean, with which I am having problems
char h; // the char
...;
public Primitive(boolean i) {
g = i;
j = 6;
}
top方法按预期工作,但是,当我尝试使用copy方法时,无论i是true还是false,布尔值都等于true.
public Primitive(Primitive i){
switch (i.j){
case 0: a = i.a; break;
case 1: b = i.b; break;
case 2: c = i.c; break;
case 3: d = i.d; break;
case 4: e = i.e; break;
case 5: f = i.f; break;
case 6: g = i.g; break;
case 7: h = i.h; break;
}
}
任何帮助将不胜感激.
编辑**
在针对所有情况测试了复制构造函数之后,我发现复制构造函数不适用于short,boolean和char数据类型.它适用于其他一切.这是我修改的代码:
public class Primitive {
private byte bytes;
private short shorts;
private int integer;
private final int DATATYPE;
private long longs;
private float floaters;
private double doubles;
private boolean bools;
private char character;
Compare compare = new Compare();
/**************************************************|
|* Constructors *|
|**************************************************/
public Primitive(byte i) {
bytes = i;
DATATYPE = 0;
}
public Primitive(short i) {
shorts = i;
DATATYPE = 1;
}
public Primitive(int i) {
integer = i;
DATATYPE = 2;
}
public Primitive(long i) {
longs = i;
DATATYPE = 3;
}
public Primitive(float i) {
floaters = i;
DATATYPE = 4;
}
public Primitive(double i) {
doubles = i;
DATATYPE = 5;
}
public Primitive(boolean i) {
bools = i;
DATATYPE = 6;
}
public Primitive(char i) {
character = i;
DATATYPE = 7;
}
public Primitive(Primitive i){
switch (i.DATATYPE){
case 0: bytes = i.bytes; break;
case 1: shorts = i.shorts; break;
case 2: integer = i.integer; break;
case 3: longs = i.longs; break;
case 4: floaters = i.floaters; break;
case 5: doubles = i.doubles; break;
case 6: bools = i.bools; break;
case 7: character = i.character; break;
}
DATATYPE = i.DATATYPE;
}
...;
}
我本来打算尝试枚举,但是却忘记了如何使用它.那,我认为整数将比ENUM更容易操作.