Java集合类的概述-Collection接口 / List接口

Java集合类的概述
集合类又称为容器,这个容器相比于数组,集合类与数组的不同之处是:数组的长度是固定的,集合的长度是可变的;数组用来存放基本类型的数据,集合用来存放对象的引用。

通常集合有List集合,set集合和map集合

Collection接口:
Collection接口的常用方法
isEmpty(),返回boolean值,用于判断当前集合是否为空
add(),将指定的对象添加到该集合
remove(),将指定的对象从该集合中移除
iterator(),返回在此Collection的元素上进行迭代的迭代器。用于遍历集合中的对象
size(),返回int型值,获取该集合中元素的个数

举例:

public class collection {
	public static void main(String[] args) {
		Collection c =new ArrayList();//实例化集合类对象
//		System.out.println("集合是不是空的"+c.isEmpty()+"集合的长度"+c.size());
		c.add("集合");
		c.add(1314);
		c.add(new Object());
		System.out.println("集合是不是空的:"+c.isEmpty()+"\t集合的长度:"+c.size());
		c.remove(1314);
		Iterator it = c.iterator();//创建迭代器
		while(it.hasNext()) {//判断是否有下一个元素
			Object o =it.next();//获取集合中的元素
			System.out.println(o);
		}
	}

}

List集合

List接口继承了Collection接口,因此包含了Collection中的所有方法。此外,List接口还定义了两个重要的方法。
get():获得指定索引位置的元素
set(int x,Object obj):将集合中指定索引位置的对象修改为指定的对象
List接口实现类有两类
①,ArrayList类实现了可变的数组,允许保存所有元素
②,LinkedList类采用链表结构保存对象。

ArrayList:更善于查找
LinkedList:更善于添加和删除

实例如下:

public class list {
	public static void main(String[] args) {
		List list = new ArrayList();//实例化list集合
//		list list = new listedlist();实例化list集合,链表结构
		list.add("春天复苏");
		list.add("夏天减肥");
		list.add("秋天到了");
		list.add("冬天来了");
		list.remove(2);
		list.add(2, "秋天又来了。。");//add()的另外一个用法,前面为索引位置,后面为添加的内容
		list.set(0, "春天被改了");//指定位置,修改内容
		list.add(null);//添加一个null
		for(int i=0;i<list.size();i++) {
			System.out.println("第"+i+"个元素是:"+list.get(i));
		}
		
//		System.out.println(list.get(3));
//		System.out.println(list.get(0));
//		list.remove(2);
		System.out.println(list.size());
	}
}
发布了17 篇原创文章 · 获赞 10 · 访问量 1476

猜你喜欢

转载自blog.csdn.net/qq_42724864/article/details/104364850