About Java ArrayList

Asked 2 years ago, Updated 2 years ago, 32 views

I finished writing a program that excludes the last number equal to X in the parameter, but it didn't work.
Example) If the list is <2,4,1,4,5>,X=4, then the list is <2,4,1,5>

public static void removeLastOccurrence(intx, ArrayList<Integer>list){
                int size = list.size();
                int OccurrenceIndex=-1;
                for(inti=size-1;i>=0;i--){
                  if(list.get(i)==x){
                      OccurrencePostion=i;
                  }
                }
                for(inti=OccurrenceIndex;i<size;i++){
                  list.set(i,list.get(i+1));
                }
                list.remove(size+1);
              }

java

2022-09-30 14:53

1 Answers

int index=list.lastIndexOf(x)
if(index>=0)
    list.remove(index);

I think remove(int) will shift the subsequent elements if you specify the middle of the list.

(If there are restrictions such as not being able to use lastIndexOf(), edit and add the question.)


2022-09-30 14:53

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.