我是java的新手,我有一个接受3个参数的方法,查询db并以arraylist形式返回结果(如[1, Java, 3, Bangalore, 10]
)。如何提取单个元素,以便我可以将每个元素分配给类似int id=1;String name=Java
的变种。
以下是
的方法ArrayList searchResult =jSearch.doJobSearch(techName, exp, city);
Iterator searchResultIterator = searchResult.iterator();
PrintWriter out = response.getWriter();
String arrayList[] = new String[searchResult.size()];
if(searchResultIterator.hasNext()){
for(int i =0; i<searchResult.size(); i++){
//searchResult.get(i)
out.println(searchResult.get(i));
}
}else{
out.println("No Job found in selected city");
}
答案 0 :(得分:1)
ArrayList在[index,element]意义上工作。
通过使用get方法,您将使用index作为参数,并返回该位置的元素。因此,如果您通过它的索引访问元素,那么您已经拥有了id和元素,但是不同的集合界面可能更适合您,就像地图一样。
答案 1 :(得分:1)
创建POJO(Plain Old Java Object)。我提供了如何在存储实时对象时使用数组列表的示例。
package com.appkart.examples;
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
将员工添加到数组列表并获取值
package com.appkart.examples;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee arun = new Employee(10, "Arun");
Employee ankit = new Employee(20, "Ankit");
Employee jon = new Employee(30, "Jon");
Employee anil = new Employee(40, "Anil");
employees.add(arun);
employees.add(ankit);
employees.add(jon);
employees.add(anil);
for (Employee employee : employees) {
int id = employee.getId();
String name = employee.getName();
System.out.println("id : "+id +" name : "+name);
}
}
}