gpt4 book ai didi

java - 有没有办法让 Arraylist 元素等于类构造函数?

转载 作者:搜寻专家 更新时间:2023-11-01 01:15:30 24 4
gpt4 key购买 nike

对于 Arraylists 的赋值,我需要将一维数组更改为数组列表,这意味着将程序从 listName.length 修改为 listName.size() 等。

我在将我的数组列表动物声明为类方法时遇到问题。我这样做了:animals.get(x) = new Dog(name, age); 但是我收到一个错误,它说左侧必须是一个变量。同样的错误发生在 new Cat(name, age);new Bird(name, age); 上。

现在,我尝试创建一个 String 变量并分配给 animals.get(x),然后将该变量分配给 new Dog(name,age) 这也不起作用,因为它要我将 new Dog(name, age) 更改为字符串(意思是更改我的变量名称,比如说 String string,到 Dog string),当我这样做时,我回到了第一个方 block ,它要求我将我的变量改回 String。

import java.util.ArrayList;
import java.util.Collection;

public class Database {
ArrayList<String> animals = new ArrayList<String>();
Database (int s) {
animals.size();
}//end of Database(s)

boolean addAnimal (int type, String name, int age) {
for (int x = 0; x < animals.size(); x++) {
if (animals.get(x) == null) {
if (type == 1) {
animals.get(x) = new Dog(name, age);
}//end of if
else if (type == 2) {
animals.get(x) = new Cat(name, age);
}//end of else if
else {
animals.get(x) = new Bird(name, age);
}//end of else
return true;
}//end of outer if
}//end of for loop
return false;
}//end of addAnimal(type, name, age)

Animal removeAnimal (String name) {
for (int x = 0; x < animals.size(); x++) {
if (animals.get(x).equals(null)) {
// If the spot in the array is null skip this index
}//end of if
else if (animals.get(x).equals(name)) {
String found = animals.get(x);
animals.at(x) = null;
System.out.print(found);
}//end of else if
}//end of for loop
return null;
}//end of removeAnimal(name)
}//end of class Database

由于我正在修改所有内容以适应数组列表,所以当用户选择添加动物时,我也必须修改上述方法。共有三种动物,狗、猫和鸟,它们都有自己的类。我希望错误'the left-hand side must be a variable'消失,我已经尝试寻找修复它的方法,但我似乎找不到与我的问题类似的解决方案.

编辑更新

我包含了我的数据库类(具有方法 addAnimal 和 removeAnimal 的类)的完整代码。

最佳答案

这里要小心,ArrayList 的 size 方法不像数组的长度那样工作:

new Object[10].length; // returns 10

List<Object> list = new ArrayList<>(10);
list.size(); // returns 0

list.addAll(Collections.nCopies(10, null));
list.size(); // returns 10

new ArrayList<>(Collections.nCopies(10, null)).size(); // returns 10

如您所见,默认情况下 ArrayList 不存储空值,相反它们根本不存储任何内容。这意味着不需要循环查找空值...您只需将值添加到列表中即可。

boolean addAnimal(int type, String name, int age) {
if (type == 1) {
animals.add(new Dog(name, age));
}
else if (type == 2) {
animals.add(new Cat(name, age));
}
else {
animals.add(new Bird(name, age));
}
return true; // You can probably make this a void method now
}

附言我在评论中看到你的 ArrayList 是字符串类型......你的动物不是字符串,所以你可以使用 new Dog(name, age).toString() 将它们转换为字符串,或者我建议将您的 ArrayList 更改为常见类型(即 ArrayList<Animal> animalsArrayList<Object> animals)。

关于java - 有没有办法让 Arraylist 元素等于类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54155382/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com