在list集合中的添加、修改、删除和遍历元素

您所在的位置:网站首页 end用法区别 在list集合中的添加、修改、删除和遍历元素

在list集合中的添加、修改、删除和遍历元素

2023-12-05 03:48| 来源: 网络整理| 查看: 265

集合与数组相似,但他的长度是可变的

list集合继承了collection接口,list集合的实现类是ArrayList()。

如下:

package com.test; import java.util.ArrayList; // import the ArrayList package import java.util.List; // import the List package public class Test { public List list; //declare List collection Test(){ this.list= new ArrayList(); //Implementation of List collection } }

list集合中的元素是有序的,可重复的。

先定义一个Student类

package com.test; public class Student { public String m_name; public int m_id; public Student(int id,String name){ this.m_name= name; this.m_id = id; } }

再定义一个类,里面包含main()方法来实现

然后在list集合中添加元素

package com.test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Test { public List list; public Test(){ this.list= new ArrayList(); } //add to student public void TestAdd(){ Student stu = new Student(1,"小明"); list.add(stu); //add student Student stu1= new Student(2,"小李"); list.add(0, stu1); //Specify the location to add the student Student[] stu2= {new Student(3,"小陈"),new Student(4,"小周")}; list.addAll(Arrays.asList(stu2)); //Add a number of student Student[] stu3= {new Student(5,"小吴"),new Student(1,"小明")}; list.addAll(2, Arrays.asList(stu3)); //Specify the location to add a number of student } public static void main(String[] args) { Test test = new Test(); test.TestAdd(); } }

在list集合中遍历元素:

public void TestFor(){ int size = list.size(); //get the length of the list for(int i=0; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3