how to remove the last element in an arraylist?

how to remove the last element in an arraylist?

how to remove the last element in an arraylist?

In this post we will give you information about How to remove the last element of an ArrayList in Java. Hear we will give you detail about How to remove the last element of an ArrayList in JavaAnd how to use it also give you demo for it if it is necessary.

we are going to learn about how to remove the last element in an arraylist?.

Consider, we have a following ArrayList:

List<Integer> prices = new ArrayList<>(Arrays.asList(1, 2, 3, 4));

To remove the last element of a ArrayList, we can use the list.remove() method by passing its index list.size()-1 as an argument to it.

The list.size()-1 gives the index of an last element.

Here is an example, that removes the last element 4 from the prices ArrayList:

import java.util.List;import java.util.Arrays;import java.util.ArrayList;public class Main{    public static void main(String[] args) {        List<Integer> prices = new ArrayList<>(Arrays.asList(1, 2, 3, 4));        prices.remove(prices.size()-1);        System.out.println(prices);    }}

Output:

[php][1,2,3][/php]

Hope this code and post will helped you for implement How to remove the last element of an ArrayList in Java. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us.

Leave a Reply

Your email address will not be published. Required fields are marked *