这问题应该是:如果是基本类型,使用new的前提是先进行初始化吧。。 比如 int[] i = new int[5]; 那如果是引用类型,像lz举例的new Integer(5);,实际上new一个类型的对象时候,如果new的是引用类型,new操作已经包含了初始化工作。 Integer源码: private final int value; /** * Constructs a newly allocated <code>Integer</code> object that * represents the specified <code>int</code> value. * * @param value the value to be represented by the * <code>Integer</code> object. */ public Integer(int value) { this.value = value; } 这是传入int类型参数的构造方法,已经对value进行了声明。
int [] a = new int[5]; new int[5];//这是数组,怎么不能new了?
int属于基本类型的,创建变量的时候不需要new 而Integer是一个封装类,new一个的时候对要创建的对象使用带参的构造方法了。int型的如果要使用new 则: int [] a = new int[5]; 这个是先在栈中开一个空间名为a,然后new再 堆中开辟5个空间
new int[5]; new Integer(5);这两个就不是一回事。不是int和Integer的问题
int [] i = new int [5] ; 这样是没错的
看了那么多,借用部分人的回答,小结一下。这两个语句几乎没有多少关联,初始化的分别是:一个数组;一个对象,而且,关键在于new int[5]是正确的。 int testint [] = new int[5]; // 允许的,创建一个大小为5类型为int的数组。 Integer testInteger = new Integer(5); // 允许的,创建一个值为5的Integer对象。
new 一个对象在堆 而new一个数组 是在栈 分配空间。new Ingeger()是在堆分配一个内存地址。而 new int[]是在栈区分配。在栈区分配了又没引用就会报错。因为引用本身就是在栈区
完全不一样 的语法 new int[5]; // 这个是定义数组的,注意[] 会在编译时提示不是语句? 而这一行 new Integer(5);//这个是调用构造方法的 注意 ()
int是基本类型,不能直接new一个对象。 Integer是int的封装类,是对象,可以同时, int testint [] = new int[5]; // 允许的,创建一个大小为5类型为int的数组。 Integer testInteger = new Integer(5); // 允许的,创建一个值为5的Integer对象。
int[] n = new int[5];
这里面设计到编译器的问题 new Integer(5);//编译器是可以赋给一个自动生成的变量的 比如这句: startActivity(new Intent(this, Game.class)); 就相当于: Intent i = new Intent(this, Game.class); startActivity(i);new int[5];//你能指望编译器随便一个变量,但是你怎么取呢?
String 等引用类型可以使用new 来构造
比如 int[] i = new int[5];
那如果是引用类型,像lz举例的new Integer(5);,实际上new一个类型的对象时候,如果new的是引用类型,new操作已经包含了初始化工作。
Integer源码:
private final int value; /**
* Constructs a newly allocated <code>Integer</code> object that
* represents the specified <code>int</code> value.
*
* @param value the value to be represented by the
* <code>Integer</code> object.
*/
public Integer(int value) {
this.value = value;
}
这是传入int类型参数的构造方法,已经对value进行了声明。
int [] a = new int[5];
new int[5];//这是数组,怎么不能new了?
而Integer是一个封装类,new一个的时候对要创建的对象使用带参的构造方法了。int型的如果要使用new 则: int [] a = new int[5]; 这个是先在栈中开一个空间名为a,然后new再
堆中开辟5个空间
new int[5];
new Integer(5);这两个就不是一回事。不是int和Integer的问题
int testint [] = new int[5]; // 允许的,创建一个大小为5类型为int的数组。
Integer testInteger = new Integer(5); // 允许的,创建一个值为5的Integer对象。
完全不一样 的语法
new int[5]; // 这个是定义数组的,注意[]
会在编译时提示不是语句?
而这一行
new Integer(5);//这个是调用构造方法的 注意 ()
int testint [] = new int[5]; // 允许的,创建一个大小为5类型为int的数组。
Integer testInteger = new Integer(5); // 允许的,创建一个值为5的Integer对象。
new Integer(5);//编译器是可以赋给一个自动生成的变量的
比如这句:
startActivity(new Intent(this, Game.class));
就相当于:
Intent i = new Intent(this, Game.class);
startActivity(i);new int[5];//你能指望编译器随便一个变量,但是你怎么取呢?
而Integer是对象,对象用new是可以的。
以后多多注意就行啦!
一个是new的数组,一个是数
我猜楼主是不是都赋值给 int 型的变量了
new int[5]; //只是返回一个数组的引用,相当于语句: a; //这里a指代变量
new Integer(5); //分配对象空间,调用对象的构造函数,返回对象的引用; 相当于语句:a.fun();
java编译器认为第一句是非法的语句,而第二句是合法的。
而c++编译器认为两句都是合法的= =!!!
当然这些都是个人YY哈,不对的地方请大家指正。