Code Junkie
Code Junkie

Reputation: 7788

How to get center 4 of an Arraylist()

I have an ArrayList. The array could contain 4 items or 4000 items. I'm looking to get the middle 4 items. My guess is to get the size / 2 with -2 +2. What is the most efficient way to do this and how do you handle odd numbers?

if (comparables.size() > 4) {
            int size = comparableVehicles.size();
            System.out.println("size " + size);
            int middle = size / 2;
            System.out.println("middle " + middle);
            int bottom = middle - 2;
            System.out.println("bottom " + bottom);

            this.comparables = comparables.subList(bottom, bottom + 4);
}

Upvotes: 2

Views: 280

Answers (1)

Mureinik
Mureinik

Reputation: 310993

The sublist call you're using is probably the most efficient way to do it. With regards to oddly sized lists - by definition, they do not have "a middle four elements". No matter how you take four elements, they will always be one element closer to one side or the other. The best you can do is make a conscience decision which side to take, and stick to it. In your code snippet, using integer division defacto makes the decision to make the "middle" closer to the beginning of the list. TL;DR - your code is fine.

Upvotes: 1

Related Questions