日期:2014-05-20  浏览次数:20720 次

关于数组赋值很少遇到的问题请大家帮助!!!!
小弟最近在做一个练习的时候遇到了一个关于数组的问题.我想在数组中保存对象,但是在赋值时,最后赋的值总会把前面的值给覆盖过.前面赋过的值在数组中都找不到了.代码如下:

public   class   SearchSpec   {

public   static   void   main(String[]   args)   {

for(int   i=0;i <commonSpecs.length;i++){
System.out.println(commonSpecs[i]);
}

}

private     static   String   name;

private     static   String   baseURL;

private     static   String   numResultsSuffix;
       
        public       static   SearchSpec[]   commonSpecs   =   {   new   SearchSpec( "lycos ", "http://lycospro.lycos.com/cqi-bin/?= "+ "pursuit?query= ", "&maxhits= "),
        new   SearchSpec   ( "hotbot ", "http://www.hotbot.com/?MT= ", "&DC= "),
        new   SearchSpec   ( "ifnoseek ", "http://infoseek.go.com/Titles?qt= ", "&nh= "),
        new   SearchSpec( "google ", "http://www.goolge.com/search?&q= ", "&num= ")
        };
       
       

public   SearchSpec(String   name,   String   baseURL,   String   numResultSuffix){
this.name   =   name;
this.baseURL   =   baseURL;
this.numResultsSuffix   =   numResultsSuffix;

}

public   static   String   makeURL(String   searchString,String   numResults){
return   (baseURL   +   searchString   +   numResultsSuffix   +   numResults);
}

public   String   getName(){
return(name);
}

public   static   SearchSpec[]   getCommonSpecs(){
return   (commonSpecs);
}

public   String   toString   (){
return( "   name: "+this.name+ "   baseURL: "+this.baseURL);
}

}

输出的结果都是4个关于goolge的,为什么其它的值都被最后的值给覆盖了呢?

------解决方案--------------------
至少也写个注释吧 看起来好辛苦的说
------解决方案--------------------
我就郁闷了 既然是存储对象 楼主为什么不用 集合
------解决方案--------------------
因为
private static String name;
private static String baseURL;
private static String numResultsSuffix;
这几个域都是static的,这个类的所有实例改变的都是同一个数据域,当然输出的结果都是4个关于goolge的.
我想你的声明应该是这样的吧:
private String name;
private String baseURL;
private String numResultsSuffix;


------解决方案--------------------
楼主注意以下两点就可以找到原因了.
1:static 对象 是所有类共用的一个实例
2:函数中的对象是通过 "引用 "(或者说传地址),而不是传值进行的赋值的.