Java 类中的数组列表
我有一个自定义类的arraylist,对于每个自定义类,我希望每个自定义类都保留自己的计算机arraylist。以下是我的课程代码:Java 类中的数组列表,java,arraylist,Java,Arraylist,我有一个自定义类的arraylist,对于每个自定义类,我希望每个自定义类都保留自己的计算机arraylist。以下是我的课程代码: class Services { public String name; public String path; public ArrayList<String> computers = new ArrayList<>(); public Services(String name, String path,
class Services {
public String name;
public String path;
public ArrayList<String> computers = new ArrayList<>();
public Services(String name, String path, String computer) {
this.name = name;
this.path = path;
this.computers.add(computer);
}
public String getName() {
return name;
}
public String getPath() {
return path;
}
public void addComputer(String computerName) {
this.computers.add(computerName);
}
}
最后,我试图编制一个服务列表。有了这些服务的列表,我需要知道服务的名称、路径以及哪些计算机拥有它们。我从文件名中获取计算机名。似乎每个服务的计算机列表都是相同的列表,而不是每个服务的不同列表。我该如何解决这个问题?我需要列一个清单吗?这似乎是多余的,而且表现不佳 很难告诉您缺少什么,因为您没有向我们提供与您的帖子相关的最重要的
main
方法
所以,根据我掌握的一些信息,这里有一个小算法,可以根据你发布的代码在所有存储的计算机上循环。这将帮助您找出您缺少的内容,否则请发布main
方法
public static void main(String args[]) {
String newComputer = "UberPC3000x";
boolean alreadyExistSomeWhere = false;
for (int i = 0; !alreadyExistSomeWhere && i < allMyServices.size(); i++) {
for (int j = 0; !alreadyExistSomeWhere && j < allMyServices.get(i).computers.size(); j++) {
alreadyExistSomeWhere = allMyServices.get(i).computers.get(j).equals(newComputer);
}
}
if (!alreadyExistSomeWhere) //Then it means it was not found and you are free to add wherever you want.
{
}
}
publicstaticvoidmain(字符串参数[]){
字符串newComputer=“UberPC3000x”;
布尔值alreadyexistwhere=false;
对于(int i=0;!alreadyExistSomeWhere&&i
请添加您所说的方法(main?)。您在哪里添加到服务的ArrayList
?能否请您进一步解释您正在尝试做什么,以及出现了什么问题?如果您可以将代码缩减到尽可能小的程度,从而仍能显示错误,那将非常有帮助。谢谢您的额外解释。我来看看硬编码的0给我带来的麻烦。我并没有真正遵循您的逻辑,但我不希望您检查z.name.contains(services[0])
。因此,只有在遍历所有服务时,当前服务与第一个服务的名称匹配时,才添加计算机名?这里似乎有点奇怪。我正在使用String[]service=y.split(+)
创建该数组。[0]始终是服务的名称,[1]始终是服务的路径。
public static void main(String args[]) {
String newComputer = "UberPC3000x";
boolean alreadyExistSomeWhere = false;
for (int i = 0; !alreadyExistSomeWhere && i < allMyServices.size(); i++) {
for (int j = 0; !alreadyExistSomeWhere && j < allMyServices.get(i).computers.size(); j++) {
alreadyExistSomeWhere = allMyServices.get(i).computers.get(j).equals(newComputer);
}
}
if (!alreadyExistSomeWhere) //Then it means it was not found and you are free to add wherever you want.
{
}
}