ArrayList get() trong java với ví dụ cụ thể

Method get(int index) trong ArrayList cho phép chúng ta lấy một phần tử tại vị trí index. Lưu ý, nếu index bé hơn không hoặc lớn hơn số lượng phần tử của ArrayList chúng ta sẽ nhận được IndexOutOfBoundException.

Code ví dụ

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> al = new ArrayList<String>();
        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

‹Previous Next›

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x