扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

arraylist怎么查询指定元素

扬州沐宇科技
2024-05-28 14:44:07
ArrayList

要查询指定元素,可以使用ArrayList的indexOf方法来查找元素在列表中的位置。这个方法会返回元素在列表中第一次出现的索引,如果元素不存在于列表中则返回-1。

例如,假设有一个名为list的ArrayList,我们想要查询元素"apple"是否在列表中,并获取其索引:

ArrayList<String> list = new ArrayList<>();
list.add("banana");
list.add("apple");
list.add("orange");

int index = list.indexOf("apple");

if (index != -1) {
    System.out.println("Element 'apple' found at index: " + index);
} else {
    System.out.println("Element 'apple' not found in the list");
}

在上面的例子中,我们首先创建一个包含一些水果的ArrayList,然后使用indexOf方法查询"apple"元素在列表中的位置。如果元素存在,则打印出其索引,否则打印出元素不存在的消息。

扫码添加客服微信