How do you retrieve the first element of a list in Java…

In Java, you can use list.get(0) to retrieve the first element of a list. This will return the element at index 0 in the list. It’s important to note that if the list is empty, this operation will throw an IndexOutOfBoundsException. Therefore, it’s advisable to check if the list is empty before using the get() method. Here is an example code:

List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

if (!list.isEmpty()) {
    int firstElement = list.get(0);
    System.out.println("第一个元素是:" + firstElement);
} else {
    System.out.println("列表为空");
}

The output results in:

第一个元素是:1
bannerAds