import java.util.Arrays;
public class AnimalsDemo{
public static void main(String[] args){
Animal[] animals = new Animal[2];
animals[0] = new Animal("dog");
animals[1] = new Animal("cat");
add(animals,new Animal("bird"));
System.out.println(Arrays.toString(animals));
}
public static void add(Animal[] animals,Animal animal){
if(animals!=null){
animals=Arrays.copyOf(animals,animals.length+1);
animals[animals.length-1] = animal;
}else{
System.out.println("数组为空");
}
}
}
class Animal{
String name;
public Animal(String name){
this.name = name;
}
public String toString(){
return this.name;
}
}
最后输出的结果是[dog,cat],调用add()方法没有达到扩容效果,为什么?求大虾帮帮忙,谢谢!
------解决方案--------------------------------------------------------
import java.util.Arrays;
public class AnimalsDemo{
public static void main(String[] args){
Animal[] animals = new Animal[2];
animals[0] = new Animal("dog");
animals[1] = new Animal("cat");
add(animals,new Animal("bird"));
System.out.println(Arrays.toString(animals)+":"+animals.length);
}
public static void add(Animal[] animals,Animal animal){
if(animals!=null){
animals=Arrays.copyOf(animals,animals.length+1);
animals[animals.length-1] = animal;
System.out.println(animals.length+"----------");
}else{
System.out.println("数组为空");
}
}
}
class Animal{
String name;
public Animal(String name){
this.name = name;
}
public String toString(){
return this.name;
}
}
执行下吧,就知道问题在哪了。
------解决方案--------------------------------------------------------