如何在Java中的搜索函数(数组)中返回多个值
我在一个类中有一个搜索函数,它通过StringDepartment of work和count搜索数组。 程序将主要询问用户他/她想要搜索什么类别。例如:图书馆;该程序应该为该特定部门中的所有书籍提供一个功能,允许用户添加书籍如何在Java中的搜索函数(数组)中返回多个值,java,arrays,search,indexing,Java,Arrays,Search,Indexing,我在一个类中有一个搜索函数,它通过StringDepartment of work和count搜索数组。 程序将主要询问用户他/她想要搜索什么类别。例如:图书馆;该程序应该为该特定部门中的所有书籍提供一个功能,允许用户添加书籍 问题是程序只返回一本书,而不是该类别中关联的所有书。函数不应返回单个索引,而应返回索引集合。 比如说 public static Collection<Integers> Searchdep(EmployeeClass EmployeeArr[], Strin
问题是程序只返回一本书,而不是该类别中关联的所有书。函数不应返回单个索引,而应返回索引集合。 比如说
public static Collection<Integers> Searchdep(EmployeeClass EmployeeArr[], String department, int size) {
List<Integer> intList = new ArrayList<Integer>();
for(int i=0; i<size; i++)
{
if(EmployeeArr[i].Department.equals(department)) {
intList.add(i);
}
}
return intList;
}
到
只需返回一个索引数组,而不是单个索引。例如:
public static List<Integer> Searchdep(EmployeeClass EmployeeArr[], String department, int size){
List<Integer> result = new ArrayList<Integer>();
for(int i=0; i<size; i++){
if(EmployeeArr[i].Department.equals(department)){
result.add(i);
}
}
return result;
}
这里最好的选择是传递一个访问者操作以应用于找到的每个员工。在Java8中,这将是一个lambda,但在Java6或Java7中,这将是一个匿名内部类
然后,您可以返回找到的计数,以便检测何时没有匹配项。您考虑过返回列表吗?但结果将显示为索引,即员工所在位置的编号,而不是员工信息。所以它应该类似于Emplist[我们拥有的索引]。ShowInfoToUser;但是,如何才能将它与您所做的结合起来呢?它给出了一个错误,说明它无法在数组上调用getinteger
Collection<Integer> returnedCollection = EmployeeClass.SearchDep(EmpList,department,count);
if(returnedCollection.isEmpty()){
JOptionPane.showMessageDialog(null,"Nothing was found");
} else {
StringBuilder str = new StringBuilder();
for(Integer integer: returnedCollection){
str.appened(EmpList[integer].ReturnStringInfo());
str.appened(", ");
}
JOptionPane.showMessageDialog(null,"Indexed are : "+ str.toString());
}
public static List<Integer> Searchdep(EmployeeClass EmployeeArr[], String department, int size){
List<Integer> result = new ArrayList<Integer>();
for(int i=0; i<size; i++){
if(EmployeeArr[i].Department.equals(department)){
result.add(i);
}
}
return result;
}