Java-如何在整数序列中查找最小值和最大值?

Java-如何在整数序列中查找最小值和最大值?,java,max,min,Java,Max,Min,我对编码相当陌生,我正试图通过使用Math.min和Math.max方法找到整数序列的最小值和最大值。我想我已经解决了大部分问题,但是当我测试它时,最小值是-2147483648,最大值是2147483647。我怎样才能改变这一点? 代码如下: /** * A class to find largest and smallest values of a sequence. **/ public class DataSet { private int smallest = Integer.

我对编码相当陌生,我正试图通过使用Math.min和Math.max方法找到整数序列的最小值和最大值。我想我已经解决了大部分问题,但是当我测试它时,最小值是-2147483648,最大值是2147483647。我怎样才能改变这一点? 代码如下:

/**
 * A class to find largest and smallest values of a sequence.
 **/
public class DataSet
{
  private int smallest = Integer.MIN_VALUE;
  private int largest = Integer.MAX_VALUE;
  /**
   * Adds in integer to sequence.
   * @param x the integer added
   */
  public void addValue(int x)
   {
    smallest = Math.min(smallest, x);
    largest = Math.max(largest, x);
   }
  /**
   * Returns the smallest value.
   * @return the smallest value
   */
  public int getSmallest() 
   {
    return smallest;
   }
  /**
   * Returns the largest value.
   * @return the largest value
   */
  public int getLargest()
    {
      return largest;
    }
}
这是测试仪:

/**
 * A class to test the DataSet class.
 */
public class DataSetTester
{
    public static void main(String[] args)
    {
        DataSet myData = new DataSet();
        myData.addValue(11);
        myData.addValue(4);
        myData.addValue(6);
        myData.addValue(9);
        System.out.println("Smallest: " + myData.getSmallest());
        System.out.println("Expected: 4");
        System.out.println("Largest: " + myData.getLargest());
        System.out.println("Expected: 11");
    }
}

将初始条件交换为
最小的
最大的
。改变

private int smallest = Integer.MIN_VALUE;
private int largest = Integer.MAX_VALUE;


因为没有
int
值小于
MIN\u值(或大于
MAX\u值
)。

为了子孙后代,在现实生活中,如果你想从集合中获取MAX和MIN元素,那么使用
SortedSet
TreeSet
这样的
排序集是一个不错的选择。这个问题需要Math.MAX和Math.MIN,但我以后会记住这一点,谢谢;int lowest=数学最大值@Tricia在这里使用调试器应该可以帮助您找到此bug。
private int smallest = Integer.MAX_VALUE;
private int largest = Integer.MIN_VALUE;