我正在玩Generics并且在我的代码中有一个轻微的问题。我的问题是如何同时迭代两个Arraylists(没有Iterator
),同时通过方法combine()
中的那两个arraylists获取对象来制作一对“couple”?我已经在代码中评论了输出应该如何显示的样子。
import java.util.*;
public class Answer {
public static void main(String[] args)
{
test_combine();
}
public static void test_combine(){
System.out.println("TESTING COMBINE");
ArrayList<String> theStrings = new ArrayList<String>(Arrays.asList(new String[]{"Hi","wow","Nuts"}));
// [Hi, wow, Nuts]
ArrayList<Integer> theInts = new ArrayList<Integer>(Arrays.asList(new Integer[]{15, -4, 42}));
// [15, -4, 42]
ArrayList<Pair2<String,Integer>> stringInts = combine(theStrings,theInts);
System.out.println(stringInts);
// [(Hi,15), (wow,-4), (Nuts,42)]
ArrayList<Double> theDoubs = new ArrayList<Double>(Arrays.asList(new Double[]{1.23, 42.1, 99.0, -2.1}));
// [1.23, 42.1, 99.0, -2.1]
ArrayList<Character> theChars = new ArrayList<Character>(Arrays.asList(new Character[]{'Z','a','!','?'}));
// [Z, a, !, ?]
ArrayList<Pair2<Double,Character>> doubChars = combine(theDoubs, theChars);
System.out.println(doubChars);
// [(1.23, Z), (42.1, a), (99.0, !), (-2.1, ?)]
}
public static <X,Y>ArrayList<Pair2<X,Y>> combine(ArrayList<X> xs, ArrayList<Y> ys)
{
ArrayList<Pair2<X,Y>> newValues = new ArrayList<>();
for(int i = 0; i < xs.size() && i < ys.size(); i++)
{
newValues.add(xs.get(i), ys.get(i));
}
}
}
答案 0 :(得分:0)
根据您发布的代码,
newValues.add(xs.get(i), ys.get(i));
应该是
newValues.add(new Pair2(xs.get(i), ys.get(i)));
假设您的Pair2
有一个可以X, Y
的构造函数。