本教程演示如何在ArrayList上执行各种操作,一些常见的操作如下:
- 将元素添加到ArrayList中。
- 从ArrayList中删除元素。
- 从ArrayList中检索元素。
- 打印ArrayList的大小。
- 检查ArrayList中是否存在元素。
- 查找ArrayList中元素的索引。
- 从ArrayList中删除所有元素。
文件:ArrayListExample.java –
package com.yiibai.tutorial; import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { List<String> list=new ArrayList<>(); /*Adding elements into the list*/ list.add("One"); list.add("Two"); list.add("Three"); list.add("Four"); list.add("Five"); System.out.println("Elements in list:"+list); /*Removing an element from the list*/ String removedEle=list.remove(0); // Remove the first element System.out.println("Element revoved:"+removedEle); System.out.println("Elements in list after removal:"+list); /*Retrieving an element in the list*/ String element=list.get(1); // Get second element System.out.println("Element at second position:"+element); /*Print size of List*/ System.out.println("Number of elements:"+list.size()); /*Check if an element exist in the list*/ System.out.println("Element exist:"+list.contains("Five")); /*Finding the index of an element*/ System.out.println("Index of 'Four' is :"+list.indexOf("Four")); /*Removing all elements from the list*/ list.clear(); System.out.println("Elements in list:"+list); } }
执行上面示例代码,得到以下结果 –
Elements in list:[One Two Three Four Five] Element revoved:One Elements in list after removal:[Two Three Four Five] Element at second position:Three Number of elements:4 Element exist:true Index of 'Four' is :2 Elements in list after clear:[]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/264152.html