【问题标题】:Java ArrayList MiddleJava ArrayList 中
【发布时间】:2010-04-25 08:19:53
【问题描述】:

如何找到一个 ArrayList 的中间?

【问题讨论】:

  • 你指的是中间还是中位数?
  • 在食指和无名指之间
  • ArrayList.imTooLazyToWriteUpAQuestionProperly().

标签: java collections arraylist


【解决方案1】:

如果您有N 项,则中间项通常定义为索引N/2 处的项(从0 开始)。

10 items
0,1,2,3,4,5,6,7,8,9
          |
          5

13 items
0,1,2,3,4,5,6,7,8,9,0,1,2
            |
            6

通常,如果您需要在索引low(包括)和high(不包括)之间找到项目的中间,则在数学上是int mid = (low + high) / 2。但是由于有限精度整数的算术溢出,正确的公式是int mid = (low + high) >>> 1;

另见

【讨论】:

  • 感谢 Bloch 文章的链接。非常有用的信息。
【解决方案2】:
ArrayList.size()/2

【讨论】:

    【解决方案3】:

    如果 ArrayList 的大小是 偶数,则使用 (ArrayList.size()/2)+1(ArrayList.size()/2) 作为中间。 如果ArrayList的大小为奇数个,则以(ArrayList.size()+1)/2为中间。

    【讨论】:

      猜你喜欢
      • 2012-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2013-12-26
      • 1970-01-01
      • 2012-05-27
      • 2018-08-07
      相关资源
      最近更新 更多