How can I sum only the first and the last item in an array list?
ex.: list = (300, 450, 150, 800, ...)

Recommended Answers

All 4 Replies

arrayList.get(0) + arrayList.get(arrayList.size() -1)

Sandro_1: If you don't mind me asking, what is it you are trying to accomplish? I'd guess you were calculating the median of the data set, but you didn't specify that the ArrayList was sorted; if it isn't, then it is hard to see what you would be getting from it. What is the purpose of this?

Sorry, about it. Yes, it is sorted list. I need to find the middle of the arrayList. It is for the school. I am a student.
Thanks for willing to help me.

Now, are you looking for the middle of the ArrayList (that is, the midpoint of the data structure), or the middle of the data set (that is, the median value of the data range)? These are two rather different things.

To get the midpoint of the ArrayList, you need to divide the length of the ArrayList by two:

midpoint = (int) Math.floor(arrylst.length / 2.0);

but there's a catch: if the ArrayList has an odd number of elements, there will be a midpoint, to either side of which will be an equal number of elements, but if it is even, then there won't be an exact midpoint and the two halves will be equal with no added midpoint element. For example:

{1, 4, 7, 11, 13}
       ^ midpoint element

{2, 3, 5, 17, 42, 69}
         ^ midpoint is between two elements

So, if you are writing (for example) a binary search routine, you may need need to determine if the ArrayList's length is even or odd before starting to work out if you have two halves, or two halves plus a midpoint.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.