3

I have an ArrayList<Integer> with values (20, 40, 60, 80, 100, 120) Is it possible to only retrieve the position 2-5 only which is 60, 80, 100 and 120? Thanks for any help.

for (DataSnapshot price : priceSnapshot.getChildren()) {
    int pr = price.getValue(Integer.class);
    priceList.add(pr); // size is 61 
}
int total = 0;
List<Integer> totalList = 
            new ArrayList<Integer>(priceList.subList(29, 34));               
for (int i = 0; i < totalList.size(); i++) {
    int to = totalList.get(i);
    total += to;
    txtPrice.setText(String.valueOf(total));
}
3
  • Kotlin or Java ? Commented Mar 3, 2019 at 7:27
  • @MehrdadPedramfar java sir! please help :( Commented Mar 3, 2019 at 7:32
  • I think below answer works. Commented Mar 3, 2019 at 7:34

1 Answer 1

6

In Java you can create a sublist (javadoc) of a list; e.g.

List<Integer> list = ...
List<Integer> sublist = list.sublist(2, 6);

Notes:

  1. The the upper bound is exclusive, so that to get the list element containing 120 we must specify 6 as the upper bound, not 5.

  2. The resulting sublist is "backed" by the original list. Therefore:

    • there is no copying involved in creating the sublist, and
    • changes to the sublist will modify the corresponding positions in the original list.
Sign up to request clarification or add additional context in comments.

18 Comments

Hi stephen the parameters of sublist are fromIndex and toIndex will the 2 became 0 index and 6 into 4? I'm a bit confused or still oni the same position?
The sublist elements are numbered from zero, as you observed. Element 2 of the old list is element 0 of the sublist, etcetera. It is done this way to conform to the List API ... which specifies that the first element of a List is at position 0.
Hey stephen I have an arraylist that has a size of 61 I only want to get index 29-34 I'm having an error IndexOutOfBoundsException I don't get why? but if I use subList(29, list.size()) No error please help
You need to explain clearly 1) how you are calling sublist and 2) where / how you are getting the exception. (My guess is that you didn't comprehend my note 1.
I'm still confused I don't get it. I edited my post can you check? Why is it not working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.