Collection 容器体系的上层接口
常用的方法与基本使用
Collection体系下所有实现类的遍历方式:
1.增强for
迭代器
public class CollectionDemo01 {
public static void main(String[] args) {
Collection col = new ArrayList();
//存储数据
col.add(1);
col.add(false);
col.add("zhangsan");
col.add('a');
col.add(new Person("lisi",18));
System.out.println(col);
//增强程序的可读性和稳定性。
Collection<String> names = new ArrayList();
names.add("zhangsan");
names.add("lisa");
names.add("wangwu");
System.out.println(names);
col.addAll(names);
System.out.println(col);
//包含
System.out.println(col.contains("zhangsan"));
System.out.println(col.containsAll(names));
//移出
System.out.println(col.remove(false));;
System.out.println(col);
System.out.println(col.size());
//遍历
for(Object o:col) {
System.out.println(o);
}
//迭代器
//1.获取迭代器对象
Iterator it = col.iterator();
//2.判断是否有下一个元素
while(it.hasNext()) {
//3.获取下一个
System.out.println(it.next());
}
}
手写集合容器
- 底层使用数组
- 要求: 容器只能存储字符串数据
public class MyListDemo02 {
public static void main(String[] args) {
MyContainer my = new MyContainer();
my.add("钢铁侠");
my.add("蜘蛛侠");
my.add("猪猪侠");
my.add("煎饼侠");
System.out.println(my.get(2));
System.out.println(my.size());
System.out.println(my);
my.replace(0, "gangtiexia");
System.out.println(my);
my.remove(2);
System.out.println(my);
int a= 5;
String[] arr = new String[++a];
System.out.println(arr.length);
System.out.println(a);
}
}
//自定义容器类
class MyContainer{
private String[] arr; //数组
private int size; //长度数组中存放数据的个数
public MyContainer() {
arr = new String[0];
}
public void add(String value) {
//备份原数组(便于拷贝使用)
String[] temp = arr;
arr = new String[size+1];
//数组拷贝
for(int i=0;i<size;i++) {
arr[i]=temp[i];
}
arr[size] = value;
//size++; //++ size原数值基础之上再+1 size = size+1
}
//根据索引删除
public void remove(int index) {
//备份原数组
String[] temp = arr;
//创建新数组
arr = new String[size-1];
//拷贝 i是原数组索引
for(int i=0;i<size;i++) {
if(i!=index) {
if(i<index) {
arr[i] = temp[i];
}else {
arr[i-1] = temp[i];
}
}
}
size--;
}
//根据索引修改 参数:索引 值
public void replace(int index,String value) {
if(index<0 || index >= size) {
throw new ArrayIndexOutOfBoundsException(index);
}
arr[index] = value;
}
//根据索引获取
public String get(int index) {
//如果根据索引进行操作,最好先对索引进行判断
if(index>=0 && index <size) {
return arr[index];
}else {
throw new ArrayIndexOutOfBoundsException(index);
}
}
public int size() {
return this.size;
}
@Override
public String toString() {
return "MyContainer [arr=" + Arrays.toString(arr) + ", size=" + size + "]";
}
}