本文介绍了在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.

推荐答案

为什么不干脆使用 remove, indexOfmin:

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个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:29