【发布时间】:2014-08-10 07:17:32
【问题描述】:
首先我为我的英语道歉,这是我第一次在 stackoverflow 上提问,所以如果我遗漏了什么,请指出。
所以我是 java 新手,在朋友的帮助下尝试二进制搜索。该代码是在使用产品ID 搜索后显示产品信息。我设法让它返回找到 Id 的索引号,但问题是当我输入多个相同的 ID 时,它只显示 1 个数据。我希望我的程序显示找到 ID-12 的所有索引。
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class MyListBinarySearch {
public static void main(String a[]){
List<Emp> empList = new ArrayList<Emp>();
empList.add(new Emp(12,"Apple,50,10-5-2014"));
empList.add(new Emp(12,"Apple,50,5-5-2014"));
empList.add(new Emp(124,"Apple,50,2-5-2014"));
empList.add(new Emp(302,"Apple,50,2-5-2014"));
empList.add(new Emp(12,"Apple,50,2-5-2014"));
Emp searchKey = new Emp(12,"String");
int index = Collections.binarySearch(empList, searchKey, new EmpComp());
System.out.println("Index of the searched key: "+index);
}
}
class EmpComp implements Comparator<Emp>{
public int compare(Emp e1, Emp e2) {
if(e1.getEmpId() == e2.getEmpId()){
return 0;
} else {
return -1;
}
}
}
class Emp {
private int empId;
private String empInfo;
public Emp(int id, String info){
this.empId = id;
this.empInfo = info;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getEmpInfo() {
return empInfo;
}
public void setEmpInfo(String empInfo) {
this.empInfo = empInfo;
}
@Override
public String toString(){
return empId+" : "+empInfo;
}
}
输出是“搜索键的索引:2” 我想显示找到搜索键的所有索引。 我怎么做 ?我需要循环吗?
【问题讨论】:
-
让我理解一下:你想在有多个正确答案的情况下进行二分搜索,并且想要返回所有正确答案?
标签: java arrays search indexing