欢迎访问宙启技术站
智能推送

Java中的数据结构函数:ArrayList

发布时间:2023-06-14 14:48:02

Java中的数据结构函数之一是ArrayList。 ArrayList是Java中的动态数组,它可以自动扩展以容纳更多的元素。 ArrayList提供了许多有用的方法,可以使您访问、插入、查找和删除存储在数组列表中的元素。在本文中,我们将讨论ArrayList的重要函数。

1. add(E element):这个函数的作用是将元素添加到ArrayList末尾。例如:

List<String> myList = new ArrayList<>();
myList.add("One");
myList.add("Two");
myList.add("Three");

这样就会在myList列表中添加三个元素。

2. add(int index, E element):这个函数的作用是将元素添加到ArrayList中特定的索引位置。例如:

List<String> myList = new ArrayList<String>();
myList.add(0, "One");
myList.add(1, "Two");
myList.add(2, "Three");

这样就会在myList列表中添加三个元素,并且在索引0处添加“One”,在索引1处添加“Two”,在索引2处添加“Three”。

3. remove(Object o):这个函数的作用是删除ArrayList中的指定元素。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
myList.remove("Two");

这样就会从myList列表中删除“Two”元素。

4. remove(int index):这个函数的作用是删除ArrayList中特定索引处的元素。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
myList.remove(1);

这样就会从myList列表中删除索引为1的元素。

5. set(int index, E element):这个函数的作用是将ArrayList中特定索引处的元素替换为给定元素。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
myList.set(1, "Four");

这样就会把索引为1的“Two”元素替换为“Four”。

6. get(int index):这个函数的作用是返回ArrayList中特定索引处的元素。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
String element = myList.get(1);

这样会获取索引为1的值即“Two”。

7. indexOf(Object o):这个函数的作用是返回ArrayList中指定元素的索引。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
int index = myList.indexOf("Two");

这样会获取“Two”的索引值即1。

8. size():这个函数的作用是返回ArrayList中元素的数量。例如:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");
myList.add("Three");
int size = myList.size();

这样会获取列表的大小,即3。

总之,ArrayList是Java中最流行的数据结构之一,它提供了许多有用的函数,可以方便地将元素添加到数组列表中,删除元素,替换元素,查找元素和获取数组列表的大小。这些函数对于Java程序员来说非常重要,因此熟练掌握它们很重要。