主要思想是创建一个方法,该方法可以一次检索所有列表的所有索引,并将此结果返回到数组或集合中……您不必存储它们,您所需要的只是对它们,您可以将它们作为参数传递给您的方法
这是创建此类方法的一些形式,如果您的搜索返回无效结果,您可以返回一个公共值:
private List<Double> firstList = new ArrayList<Double>();
private List<Double> secondList = new ArrayList<Double>();
private List<Double> thirdList = new ArrayList<Double>();
private static final double OUT_OF_BOUNDS = -1;
// just to initialize the arrays
private void initializeLists() {
// dont pay attention to this
for (double d1 = 0, d2 = 500, d3 = 5000; d1 < 50; d1++, d2++, d3++) {
firstList.add(d1);
secondList.add(d2);
thirdList.add(d3);
}
}
// create a method to retrieve data from both lists, and return it in an array or even
// a new list
private double[] apply(int index) {
if (index < firstList.size() && index < secondList.size()) {
if (index >= 0) {
return new double[] { firstList.get(index), secondList.get(index) };
}
}
return new double[] { OUT_OF_BOUNDS, OUT_OF_BOUNDS };
}
// you can pass those lists as parameters
private double[] apply(int index, List<Double> firstList, List<Double> secondList) {
if (index < firstList.size() && index < secondList.size()) {
if (index >= 0) {
return new double[] { firstList.get(index), secondList.get(index) };
}
}
return new double[] { OUT_OF_BOUNDS, OUT_OF_BOUNDS };
}
// you can even pass undefined number of lists (var-args)and grab there values at onnce
private double[] apply(int index, List<Double>... lists) {
int listsSize = lists.length;
if (index >= 0) {
double[] search = new double[listsSize];
for (int listIndex = 0; listIndex < listsSize; listIndex++) {
List<Double> currentList = lists[listIndex];
if (index < currentList.size()) {
search[listIndex] = currentList.get(index);
} else {
search[listIndex] = OUT_OF_BOUNDS;
}
}
return search;
}
double[] invalidSearch = new double[listsSize];
for (int i = 0; i < listsSize; i++) {
invalidSearch[i] = OUT_OF_BOUNDS;
}
return invalidSearch;
}
// now the work
public void combineLists() {
initializeLists();
double[] search = null;
// search for index Zero in both lists
search = apply(0);
System.out.println(Arrays.toString(search));
// result : [0.0, 500.0]
// search for index One in both list parameters
search = apply(1, firstList, secondList);
System.out.println(Arrays.toString(search));
// result : [1.0, 501.0]
// search for index Two in var-args list parameters
search = apply(2, firstList, secondList, thirdList);
System.out.println(Arrays.toString(search));
// result : [2.0, 502.0, 5002.0]
// search for wrong index
search = apply(800);
System.out.println(Arrays.toString(search));
// result : [-1.0, -1.0]
// search for wrong index
search = apply(800, firstList, secondList);
System.out.println(Arrays.toString(search));
// result : [-1.0, -1.0]
// search for wrong index
search = apply(800, firstList, secondList, thirdList);
System.out.println(Arrays.toString(search));
// result : [-1.0, -1.0,-1.0]
}