How to use ArrayList's get() method

后端 未结 5 1995
长发绾君心
长发绾君心 2021-01-04 13:27

I\'m new to java (& to OOP too) and I\'m trying to understand about the class ArrayList but I don\'t understand how to use the get(). I tried searching in net, but could

5条回答
  •  萌比男神i
    2021-01-04 14:05

    ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

    public Element get(int index)
    

    Example : In below example we are getting few elements of an arraylist by using get method.

    package beginnersbook.com;
    import java.util.ArrayList;
    public class GetMethodExample {
       public static void main(String[] args) {
           ArrayList al = new ArrayList();
           al.add("pen");
           al.add("pencil");
           al.add("ink");
           al.add("notebook");
           al.add("book");
           al.add("books");
           al.add("paper");
           al.add("white board");
    
           System.out.println("First element of the ArrayList: "+al.get(0));
           System.out.println("Third element of the ArrayList: "+al.get(2));
           System.out.println("Sixth element of the ArrayList: "+al.get(5));
           System.out.println("Fourth element of the ArrayList: "+al.get(3));
       }
    }
    

    Output:

    First element of the ArrayList: pen
    Third element of the ArrayList: ink
    Sixth element of the ArrayList: books
    Fourth element of the ArrayList: notebook
    

提交回复
热议问题