在Java中删除arraylist中最小的2个元素? [英] Removing the smallest 2 elements in an arraylist in java?

查看:132
本文介绍了在Java中删除arraylist中最小的2个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个整数数组列表,我需要计算除最小的两个整数外的所有整数的平均值.我一直在尝试不同的方法,但是我想做的就是找到min1,将其删除,然后找到min2,然后将其删除.

I have an arraylist of integers, i need to compute the average of the integers excluding the smallest two integers. I keep trying different ways of doing this but think what I want to do is find min1, remove it and then find min2 then remove that.

public double computeAverageWithoutLowest2()
  {
    ArrayList<Student> newscores = new ArrayList<Student>(scores);
    int newtotalScores=0;
    int newavg=0; 
    int min1 = 0;
    int min2 = 0;

    min1 = newscores.get(0).getScore();

    for (int i = 0; i< newscores.size(); i++)
    {
      if (newscores.get(i).getScore() < min1)
      {
        min1 = newscores.get(i).getScore();
      }
    }

现在我要从阵列列表中删除min1.我显然尝试过newscores.remove(min1);这不起作用.如何找出数组min1中的哪个位置,然后将其删除?

now I want to remove min1 from my arraylist. I have obviously tried newscores.remove(min1); which does not work. How can I figure out what spot in the array min1 is and then delete it?

任何帮助都将非常感谢!

Any help would be great thanks!!

好的,现在在查看注释后,我将代码更改为:

Alright so now after looking at the comments I changed my code to:

ArrayList<Student> newscores = new ArrayList<Student>(scores);
    int newtotalScores=0;
    int newavg=0; 

    int minPos1 = 0;
    int minPos2 = 0;
    int min1 = newscores.get(0).getScore();
    int min2 = newscores.get(0).getScore();

    for(int i = 0; i < newscores.size(); i++) 
    {
      if(newscores.get(i).getScore() < min1) 
      {
        min1 = scores.get(i).getScore();
        minPos1 = i;
      } 
    }
    newscores.remove(minPos1);


    for(int j = 0; j < newscores.size(); j++)
    {
      if(newscores.get(j).getScore() < min2)
      {
        min2 = scores.get(j).getScore();
        minPos2 = j;
      }
    }
    newscores.remove(minPos2);

这种方法可以删除min1,但不能删除min2,而是只删除与min1相同的位置.

This way works to remove min1, but does not work to remove min2 instead it just removes the same position that min1 removed.

推荐答案

为什么不简单地使用

Why don't you simply use remove, indexOf and min:

newscores.remove(newscores.indexOf(Collections.min(newscores)));

如果要删除两个最小的项目,请重复两次.

Do it twice if you want to remove the two smallest items.

这篇关于在Java中删除arraylist中最小的2个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆