ArrayList类的使用
2024-10-09 05:44:03
ArrayList常用类方法
(1)添加元素
public boolean add(E element) 在集合末端添加一个元素
public void add(int index,E element) 在指定的索引处添加一个元素
(2)获取元素
public E get(int index) 返回指定索引处的元素
(3)删除元素
public boolean remove(Object o) 删除指定的元素,返回删除是否成功
public E remove(int index) 删除指定索引处的元素,返回被删除的元素
(4)修改元素
public E set(int index,E element) 修改指定索引处的元素,返回被修改的元素
(5)获取集合长度
public int size() 返回集合中的元素的个数
示例:
import java.util.ArrayList; public class Demo01 {
public static void main(String[] args) {
// 创建集合对象
ArrayList<String> arrayList=new ArrayList<String>(); //添加String类型数据, public boolean add(E element)
boolean b1 = arrayList.add("hello");
arrayList.add("world");
arrayList.add("inspur"); System.out.println(arrayList);
System.out.println(b1); //添加String类型数据, public void add(int index, E element)
arrayList.add(1,"you");
arrayList.add(1,"we"); System.out.println(arrayList); //获取数据 public E get(int index)
System.out.println(arrayList.get(2)); //删除数据 public boolean remove(Object obj) boolean b2=arrayList.remove("Hello");
boolean b3=arrayList.remove("hello");
System.out.println("b2:"+b2+" b3:"+b3);
System.out.println(arrayList); //删除数据 public E remove (int index)
String str1=arrayList.remove(0);
System.out.println("str1:"+str1);
System.out.println(arrayList); //修改数据 public E set(int index, E element) String str2 = arrayList.set(0,"first");
System.out.println("str2:"+str2);
System.out.println(arrayList); //获取集合长度
int arrayLength = arrayList.size();
System.out.println(arrayLength); }
}
输出结果为:
[hello, world, inspur]
true
[hello, we, you, world, inspur]
you
b2:false b3:true
[we, you, world, inspur]
str1:we
[you, world, inspur]
str2:you
[first, world, inspur]
3
ArrayList 集合类的遍历
(1)for 循环遍历 (2)foreach 遍历
示例:
public class Demo02 {
public static void main(String[] args) {
// 创建集合对象
ArrayList<String> arrayList=new ArrayList<String>(); //添加String类型数据
arrayList.add("hello");
arrayList.add("world");
arrayList.add("inspur"); System.out.println(arrayList); // for 循环遍历
System.out.println("使用for循环进行遍历");
for(int i=0;i<arrayList.size();i++){
System.out.print(arrayList.get(i)+"\t");
}
System.out.println(); // foreach 进行遍历
System.out.println("使用foreach进行遍历");
for (String str:arrayList) {
System.out.print(str+"\t");
}
}
}
输出结果为:
[hello, world, inspur]
使用for循环进行遍历
hello world inspur
使用foreach进行遍历
hello world inspur
最新文章
- Microservice架构模式简介
- iOS 疑难杂症 — — Swift debugger 无法在控制台 po 变量值的问题
- gcc编译过程简述
- SQL一次查出多个字段的COUNT值
- xcoj1062
- poj3675 求多边形与圆的面积交
- linux安装-版本选择-终极决定
- @perproty and @synthesize
- jQuery库(noConflict)冲突解决机制
- [UWP]用Shape做动画
- KVM之Live Migration
- JDBCTemplate与模板设计方法(二)
- JSP三大指令 六大内置对象
- Mybatis_4.接口类和XML同时使用
- 什么是IIS ?
- mysql数据库忘记密码时如何修改
- Java编程的逻辑 (85) - 注解
- 自然语言处理(英文演讲)_2-gram
- eclipse报Access restriction: The type &#39;BASE64Decoder&#39; is not API处理方法
- TOAD连接ORACLE而不装ORACLE 客户端的方法