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

本文介绍了Java编程中List集合的基本操作,包括如何添加元素、遍历元素、修改元素。重点讲解了ArrayList作为List集合实现类的使用,并通过示例代码展示了具体的操作步骤。
摘要由CSDN通过智能技术生成

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

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<Student> list;
	
	public Test(){
		this.list= new ArrayList<Student>();
	}
	//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集合中遍历元素:

<pre name="code" class="java">
public void TestFor(){
	int size = list.size();				//get the length of t
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值