【发布时间】:2010-04-25 08:19:53
【问题描述】:
如何找到一个 ArrayList 的中间?
【问题讨论】:
-
你指的是中间还是中位数?
-
在食指和无名指之间
-
ArrayList.imTooLazyToWriteUpAQuestionProperly().
标签: java collections arraylist
如何找到一个 ArrayList 的中间?
【问题讨论】:
标签: java collections arraylist
如果您有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;
【讨论】:
ArrayList.size()/2
【讨论】:
如果 ArrayList 的大小是 偶数,则使用 (ArrayList.size()/2)+1 或 (ArrayList.size()/2) 作为中间。 如果ArrayList的大小为奇数个,则以(ArrayList.size()+1)/2为中间。
【讨论】: