博客
关于我
Collection接口_List接口_ArrayList集合常用方法
阅读量:558 次
发布时间:2019-03-09

本文共 1579 字,大约阅读时间需要 5 分钟。

Collection接口_List接口_ArrayList集合常用方法

Collection是所有单列集合的父接口,因此在Collection中定义了单列集合(List和Set)通用的一些方法,这些方法可用于操作所有的单列集合。

Collection接口的方法:

List接口

List接口继承自Collection接口,是单列集合的一个重要分支,习惯的会将实现了List接口的对象称为List集合。在List接口中允许出现重复的元素,所有的元素都是以一种线性方式进行存储的,在程序中可以通过索引来访问集合中的指定元素。List还有一个特点就是元素有序,即元素的存入顺序跟取出顺序是一致的。

List作为Collection集合的子接口,不但继承了Collection接口中的所有方法,而且还增加了一些根据元素索引来操作集合的特有方法。

import java.util.ArrayList;import java.util.Collection;public class _02_TestList {	public static void main(String[] args) {		// TODO Auto-generated method stub		Collection
c = new ArrayList
(); System.out.println(c.isEmpty()); // 判断里面是否为空,为空返回true System.out.println(c.size()); c.add("Collection"); // 添加 c.add("String"); System.out.println(c); c.remove("String"); // 移除 System.out.println(c); c.clear(); // 清空 System.out.println(c); }}

 

ArrayList集合

ArrayList是List的一个实现类,它是程序中最常见的一种集合。在ArrayList内部封装了一个长度可变的数组对象,当存入的元素长度超过数组长度时,ArrayList会在内存中分配一个更大的数组来存储这些元素,因此可以将ArrayList集合看作是一个长度可变的数组。

ArrayList集合中大部分方法都是从Collection和List中继承过来的,其中add()方法和get()方法用于实现元素的读取。

import java.util.*;public class Exceptle{    public static void main(String[] args){        ArrayList list = new ArrayList();     // 创建ArrayList 集合        list.add("str1");                             list.add("str2");        list.add("str3");        list.add("str4");        System.out.println("集合长度:"+list.size());            System.out.println("集合长度:"+list.get(1));       }}

 

注:ArrayList 集合的底层是使用一个数组来保存元素,在增加和移除时指定位置的元素时,会导致创建新的数组,效率较低,因此不适合做大量的增删操作,但这种数组的结构允许程序通过索引的方式来访问元素,因此使用ArrayList 集合查找元素很便捷。

 

 

转载地址:http://bwgsz.baihongyu.com/

你可能感兴趣的文章
Node.js安装及环境配置之Windows篇
查看>>
Node.js安装和入门 - 2行代码让你能够启动一个Server
查看>>
node.js安装方法
查看>>
Node.js官网无法正常访问时安装NodeJS的方法
查看>>
node.js模块、包
查看>>
node.js模拟qq漂流瓶
查看>>
node.js的express框架用法(一)
查看>>
Node.js的交互式解释器(REPL)
查看>>
Node.js的循环与异步问题
查看>>
Node.js高级编程:用Javascript构建可伸缩应用(1)1.1 介绍和安装-安装Node
查看>>
nodejs + socket.io 同时使用http 和 https
查看>>
NodeJS @kubernetes/client-node连接到kubernetes集群的方法
查看>>
NodeJS API简介
查看>>
nodejs Error: request entity too large解决方案
查看>>
Nodejs express 获取url参数,post参数的三种方式
查看>>
nodejs http小爬虫
查看>>
nodejs libararies
查看>>
vue3+element-plus 项目中 el-switch 刷新后自动触发change?坑就藏在这里!
查看>>
nodejs npm常用命令
查看>>
nodejs npm常用命令
查看>>