views:

92

answers:

3

How to find the middle of an ArrayList ?

+5  A: 
ArrayList.size()/2
Tim Bender
+4  A: 

If you have N items, the middle item is usually defined as item at index N/2 (0-based).

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

Generally, if you need to find the middle of items between index low (inclusive) and high (exclusive), it's mathematically int mid = (low + high) / 2. But due to arithmetic overflow in limited-precision integer, the proper formula is int mid = (low + high) >>> 1;

See also

polygenelubricants
Wow, what a long answer on such a simple question. Where do you get courage?
Martijn Courteaux
+1  A: 

If the size of ArrayList is even in number, then use (ArrayList.size()/2)+1 or (ArrayList.size()/2) as the middle. If the size of ArrayList is odd in number, then use (ArrayList.size()+1)/2 as the middle.

Venkats