比较2个数组列表之间的值

时间:2011-12-16 08:46:33

标签: java arraylist

我在比较不同数组列表中的值时遇到了一些问题 从这个值,我需要比较并找到最大n min

这是我的编码:

    ArrayList<Integer> S1 = new ArrayList<Integer>(5);  
    ArrayList<Integer> S2 = new ArrayList<Integer>(5);  
    ArrayList<Integer> S3 = new ArrayList<Integer>(5);  

    S1.add(49);S1.add(68);S1.add(91);S1.add(91);S1.add(12);  
    S2.add(85);S2.add(56);S2.add(62);S2.add(72);S2.add(94);  
    S3.add(76);S3.add(28);S3.add(52);S3.add(96);S3.add(70);

示例:我想比较49,85,76

3 个答案:

答案 0 :(得分:2)

以下是如何迭代这三个列表的方法:

//TODO for the reader: check that the lists have the same length
for (int i = 0; i < s1.size(); i++) {
  int s1 = S1.get(i);
  int s2 = S2.get(i);
  int s3 = S3.get(i);
  // compare s1, s2 and s3 here...
}

由于这看起来像是家庭作业,我将比较逻辑留作读者的练习。

答案 1 :(得分:1)

构建一个新列表(在您的第一个元素的示例列表中)并在那里找到min / max,例如使用Collections类。

答案 2 :(得分:0)

首先,您可以通过

轻松添加列表中的元素
 ArrayList<Integer> s1 = new ArrayList<Integer>(5);  
 s1.addAll(Arrays.asList(49, 68, 91, 12));

此外,避免将大写字母用于变量名称,这些名称是为类名保留的。

现在,回答你的问题。这可以使用一个简单的循环来完成:

ArrayList<Integer> min = new ArrayList<Integer>(5);  
ArrayList<Integer> max = new ArrayList<Integer>(5);  

// ASSUMPTION: s1, s2 and s3 has the same length, or at least s1.length is the 
// shortest list
for (int i = 0; i < s1.length; i++) {
  max.add(Math.max(Math.max(s1.get(i), s2.get(i)), s3,get(i)));
  min.add(Math.min(Math.min(s1.get(i), s2.get(i)), s3,get(i)));
}

你最终会得到两个阵列。每个包含特定索引值的最小值或最大值。我希望这就是你想要的。

相关问题