Integer内有一个private int value;保存他的值 Integer的构造函数是这样的 public Integer(int value) { this.value = value; } 然后,Integer封装了很多int和其他类型转换等常用方法 比如toUnsignedString和compareTo private static String toUnsignedString(int i, int shift) { char[] buf = new char[32]; int charPos = 32; int radix = 1 << shift; int mask = radix - 1; do { buf[--charPos] = digits[i & mask]; i >>>= shift; } while (i != 0); return new String(buf, charPos, (32 - charPos)); } public int compareTo(Integer anotherInteger) { int thisVal = this.value; int anotherVal = anotherInteger.value; return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1)); }
The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. Integer 是一个包装类,简单看,就是一个类。new了一下就是一个Integer对象;而 int 是基本数据类型,直接用 运算符 加加减减,因为JAVA里面没有运算符重载,所以你不能将 Integer 对象直接++ --。 两个东西各有各的用处。
Integer是继承自Object的
所以Integer封装了很多方法,比如一些static的工具性方法
Integer n=new Integer(47);与int n=47;两种赋值是否一样的,即便Integer类有更多的方法又怎么了, 是否可以把 Integer n=new Integer(47)理解为Integer类的一种赋值形式?我是菜鸟,也请各位能解释的详细一点吧,如果不同的话
Integer n=new Integer(47);n是一个对象 n继承Number, Number继承Object n为Object所以它具有对象的一些属性和方法。
而int n=47;n为类型。 不具备对象的一些属性和方法。
通常我们建议使用n=47定义一个整数。但在java的很多方法中参数或返回值为Object 这个使用就要使用Integer n=new Integer(47);定义
Integer的构造函数是这样的
public Integer(int value) {
this.value = value;
}
然后,Integer封装了很多int和其他类型转换等常用方法
比如toUnsignedString和compareTo private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << shift;
int mask = radix - 1;
do {
buf[--charPos] = digits[i & mask];
i >>>= shift;
} while (i != 0); return new String(buf, charPos, (32 - charPos));
}
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
}
两个东西各有各的用处。