day07--常用类-ArrayList-其他常用方法说明(重点)
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
package com.inmind.arraylist03;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/*
|
||||
10.常用类-ArrayList-其他常用方法说明
|
||||
添加:
|
||||
void add(int index, E element) 在此列表中的指定位置插入指定的元素
|
||||
public boolean add(E e):将指定的元素添加到此集合的尾部。
|
||||
|
||||
删除
|
||||
public E remove(int index) :移除此集合中指定位置上的元素。返回被删除的元素。
|
||||
boolean remove(Object o) 从列表中删除指定元素的第一个出现(如果存在)。
|
||||
|
||||
修改:
|
||||
E set(int index, E element) 用指定的元素替换此列表中指定位置的元素。
|
||||
|
||||
查询
|
||||
public E get(int index) :返回此集合中指定位置上的元素。返回获取的元素。
|
||||
|
||||
public int size() :返回此集合中的元素数。遍历集合时,可以控制索引范围,防止越界。
|
||||
boolean contains(Object o) 如果此列表包含指定的元素,则返回 true
|
||||
*/
|
||||
public class Demo07 {
|
||||
public static void main(String[] args) {
|
||||
//创建一个存放字符串的集合容器
|
||||
ArrayList<String> list = new ArrayList<>();
|
||||
/*
|
||||
添加:
|
||||
void add(int index, E element) 在此列表中的指定位置插入指定的元素 【插队】
|
||||
public boolean add(E e):将指定的元素添加到此集合的尾部。 【排队】
|
||||
*/
|
||||
list.add("杨幂");
|
||||
list.add("迪丽热巴");
|
||||
list.add("白鹿");
|
||||
list.add("王宝强");
|
||||
list.add("白鹿");
|
||||
System.out.println(list);
|
||||
//让张三插队到王宝强的前面
|
||||
list.add(2,"张三");
|
||||
System.out.println(list);
|
||||
|
||||
/*
|
||||
删除
|
||||
public E remove(int index) :移除此集合中指定位置上的元素。返回被删除的元素。
|
||||
boolean remove(Object o) 从列表中删除指定元素的第一个出现(如果存在)。
|
||||
*/
|
||||
//删除碍眼的张三
|
||||
String removedValue = list.remove(2);
|
||||
System.out.println("removedValue:"+removedValue);
|
||||
System.out.println(list);
|
||||
|
||||
//删除李四
|
||||
System.out.println(list.remove("李四"));//没有则删除失败
|
||||
System.out.println(list.remove("白鹿"));//有则删除成功
|
||||
System.out.println(list);
|
||||
|
||||
/*
|
||||
修改:
|
||||
E set(int index, E element) 用指定的元素替换此列表中指定位置的元素。
|
||||
*/
|
||||
//请将王宝强,改名为王宝宝
|
||||
String preValue = list.set(2, "王宝宝");
|
||||
System.out.println("修改之前的值为:"+preValue);
|
||||
System.out.println(list);
|
||||
|
||||
/*
|
||||
查询
|
||||
public E get(int index) :返回此集合中指定位置上的元素。返回获取的元素。
|
||||
*/
|
||||
String res = list.get(1);
|
||||
System.out.println(res);
|
||||
System.out.println(list);
|
||||
|
||||
//经过操作之后集合容器中的数据的长度是多少呢??
|
||||
System.out.println(list.size());
|
||||
|
||||
//集合如何获取集合中对应的所有的元素值呢??for循环遍历
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
String s = list.get(i);
|
||||
System.out.println(s);
|
||||
}
|
||||
|
||||
//快捷方式:list.fori list.forr
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
System.out.println(list.get(i));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user