Reputation: 73
How do I find the middle element of an ArrayList? What if the size is even or odd?
Upvotes: 4
Views: 15733
Reputation: 165
if the arraylist is odd : list.get(list.size() / 2); if the arratlist is even: list.get((list.size() / 2) -1);
Upvotes: 2
Reputation: 21
If you have a limitation for not using arraylist.size() / arraylist.length() method; you can use two iterators. One of them iterates from beginning to the end of the array, the other iterates from end to the beginning. When they reach the same index on the arraylist, then you find the middle element.
Some additional controls might be necessary to assure iterators wait each other before next iteration, you should not miss the meeting point..etc.
While iterating, for both iterators you keep total number of elements they read. So they should iterate one element in a cycle. With cycle, I mean a process including these operations:
The iterators might need to read more than one index to read an element. In other words you should skip one element in one cycle, not one index.
Upvotes: 0
Reputation: 17630
It turns out that a proper ArrayList
object (in Java) maintains its size as a property of the object, so a call to arrayList.size()
just accesses an internal integer. Easy.
/**
* Returns the number of elements in this list.
*
* @return the number of elements in this list
*/
public int size() {
return size;
}
It is both the shortest (in terms of characters) and fastest (in terms of execution speed) method available.
So, presuming you want the "middle" element (i.e. item 3 in a list of 5 items -- 2 items on either side), it'd be this:
Object item = arrayList.get((arrayList.size()/2)+1);
Now, it gets a little trickier if you are thinking about an even sized array, because an exact middle doesn't exist. In an array of 4 elements, you have one item on one side, and two on the other.
If you accept that the "middle" will be biased to ward the end of the array, the above logic also works. Otherwise, you'll have to detect when the size of the elements is even and behave accordingly. Wind up your propeller beanie friends...
Object item = arrayList.get((arrayList.size()/2) + (arrayList.size() % 2));
Upvotes: 4