[英]Nested Array list in Java
我在询问用户候选人信息然后我正在调用“addcandidate”方法并且我试图在数组列表中保存候选人信息。顺便说一下,如果用户想要添加新的候选人我会再次获得他们的信息并想要添加我的 arraylist。但是它只持有最后一个候选人信息
我的 addcandidate 方法代码是这样的
static void addcandidate(String name,String surname,String adress,String talent){
List<List<Object>>listoflist=new ArrayList<>();
List<Object>candidatelist=new ArrayList<Object>();
candidatelist.add(name);
candidatelist.add(surname);
candidatelist.add(adress);
candidatelist.add(talent);
listoflist.add(candidatelist);
System.out.println(listoflist);
}
以及询问候选人信息的mycode
while (true){
Scanner oku=new Scanner(System.in);
System.out.println("what kind of process do you want ? 1-Add Candidate 2-Add Employee " +
"3- add employee from candidate 4-search candidate for talent 5-print wiew");
int processtype=oku.nextInt();
if (processtype==1){
System.out.println("please enter candidate name");
String cname=oku.next();
System.out.println("please enter candidate sname");
String csname=oku.next();
System.out.println("please enter candidate adress");
String cadress=oku.next();
System.out.println("please enter candidate talent");
String ctalent=oku.next();
Candidate.addcandidate(cname,csname,cadress,ctalent);
System.out.println("do you want to continue");
String answer=oku.next();
if (answer=="n"){
break;
}
}
}
我的 output 期望是这样的 [[tom,jhn,usa,it],[peter,parker,england,language]]
您需要在方法addcandidate
listoflist
比如像这样。
import java.util.ArrayList;
import java.util.List;
public class Main {
public static List<List<Object>> listoflist = new ArrayList<>();
public static void main(String[] args) {
addcandidate("Name 1", "Surname 1", "Street 1", "Music");
addcandidate("Name 2", "Surname 2", "Street 2", "Singing");
addcandidate("Name 3", "Surname 3", "Street 3", "Sport");
}
public static void addcandidate(String name, String surname, String adress, String talent){
List<Object> candidatelist = new ArrayList<Object>();
candidatelist.add(name);
candidatelist.add(surname);
candidatelist.add(adress);
candidatelist.add(talent);
listoflist.add(candidatelist);
System.out.println(listoflist);
}
}
执行此代码的结果。
[[Name 1, Surname 1, Street 1, Music]]
[[Name 1, Surname 1, Street 1, Music], [Name 2, Surname 2, Street 2, Singing]]
[[Name 1, Surname 1, Street 1, Music], [Name 2, Surname 2, Street 2, Singing], [Name 3, Surname 3, Street 3, Sport]]
您的listoflist
声明位于addCandiadte
方法中,因此每次创建数组列表时,最后您都会拥有最后创建的列表。 执行以下操作:
// outside addCandiadte method
List<List<Object>>listoflist=new ArrayList<>();
static void addcandidate(String name,String surname,String adress,String talent){
List<Object>candidatelist = new ArrayList<Object>();
candidatelist.add(name);
candidatelist.add(surname);
candidatelist.add(adress);
candidatelist.add(talent);
listoflist.add(candidatelist);
System.out.println(listoflist);
}
希望你明白了。 另外使用List<String>candidatelist
而不是List<Object>candidatelist
以获得更好的可读性和类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.