import java.util.Hashtable;public class TObjectArray
{
Hashtable table[];
int i[];
public static void main(String[] args)
{
TObjectArray object=new TObjectArray();
object.test1();
object.test2();
}
public void test1()
{
table=new Hashtable[1];
table[0]=new Hashtable();
table[0].put("1", "abc");
table=new Hashtable[2];
table[1]=new Hashtable();
table[1].put("2", "efg");
//System.out.println(table[0].get("1")); 这句错
System.out.println(table[1].get("2"));//这句没错
}
public void test2()
{
i=new int[1];
i[0]=0;
i=new int[2];
i[1]=1;
for (int j = 0; j < i.length; j++)
{
System.out.println(i[j]);
}
}}
//上面的代码,是动态改变两种数组的维数,一种是基本类型的数组,一种是对象数组,发现,基本类型的数组,是可以动态改变维数,并保留原有的数值,但是对象型数组都不可以了,每次改变维数,原来的对象都会丢失。有人能解释一下吗?
{
Hashtable table[];
int i[];
public static void main(String[] args)
{
TObjectArray object=new TObjectArray();
object.test1();
object.test2();
}
public void test1()
{
table=new Hashtable[1];
table[0]=new Hashtable();
table[0].put("1", "abc");
table=new Hashtable[2];
table[1]=new Hashtable();
table[1].put("2", "efg");
//System.out.println(table[0].get("1")); 这句错
System.out.println(table[1].get("2"));//这句没错
}
public void test2()
{
i=new int[1];
i[0]=0;
i=new int[2];
i[1]=1;
for (int j = 0; j < i.length; j++)
{
System.out.println(i[j]);
}
}}
//上面的代码,是动态改变两种数组的维数,一种是基本类型的数组,一种是对象数组,发现,基本类型的数组,是可以动态改变维数,并保留原有的数值,但是对象型数组都不可以了,每次改变维数,原来的对象都会丢失。有人能解释一下吗?
楼主的说法是错误的之所以出现这种情况, 是因为: Java会给数组对象的元素赋初值. 对于基本类型, 就是逻辑上的0值(int 0; double 0.0; boolean false等等), 对于对象数组, 则将赋null值.//System.out.println(table[0].get("1")); 这句错, 是引用了null, 抛出NullPointerException.System.out.println(table[1].get("2"));//这句没错, 因为table[1]你已经赋了值, 当然不会出错...对于基本类型的数组, 其初值就是0, 所以你输出当然不会出错了
==================
正解!i=new int[1];
i[0]=0;
你改成
i=new int[1];
i[0]=2;
试试??