Java-ArrayList集合

需要重点强调一下 Java中的集合是多种数据结构的统称 并不等同与c++中的set概念

其中 ArrayList就是其中的一种

集合和数组的对比

  • 长度 集合的长度是自动扩容自动收缩的
  • 存储类型 集合中存储基本数据类型时 需要对应的包装类

创建集合对象

不同于数组 集合在创建对象时 如果想对数据类型加以限制 就需要用到泛型这一概念

1
2
3
4
5
ArrayList<String> list=new ArrayList<>()  // 后面尖括号里面的String可以省略

// 下面这种初始化是错误的 集合不能直接存储基本数据类型
ArrayList<int> list=new ArrayList<>() // error!!
ArrayList<Integer> list =new ArrayList<>()

常见的包装类

基本数据类型 包装类
byte Byte
short Short
char Character
int Integer
long Long
float Float
double Double
boolean Boolean

集合的增删改查

不止是ArrayList这个集合 其他集合的常用方法也无非是增删改查

1
2
3
4
5
6
7
8
9
10
list.add()
list.remove()
// remove 有两个中重载方法 一个是放index 一个是直接放字符串
// index 形式放回的是删除的str 字符串返回的是boolean
list.set(int index,String s)
//把s替换到index的内容
list.get(int index)
// 查询索引
list.size()
//集合的长度