JAVA学习历程记录(三)
集合Collection
集合中只能存储引用数据类型
常用API
Collection <String> collection = new ArrayList<>(); //collection是接口,不能直接实例化
collection.add("123"); //增
collection.clear(); //清除数据
collection.remove("123") //删
collection.size //集合里元素的实际长度
collection.contains("123") //是否包含某一个元素
List接口
继承自Collection接口,有三大实现类:ArrayList、LinkedList、Vector
List接口特点
有序的集合
提供了带索引的方法
允许存储重复的元素
常用API
List<String> list = new ArrayList<>();
list.add("123");
list.indexOf("123");
list.lastIndexOf("123");
list.remove(1);
list.set(1,"1234");
List<String> sublist = list.sublist(1,3);
ArrayList
ArrayList特性
ArrayList默认容量是10
底层使用的是数组
查询速度快
增删速度慢
线程不安全
扩容方式:每次扩容是原来容量的3/2
重写ArrayList类
public class ArrayListPratice {
private int size = 0;
private String data[];
//默认容量是10
public ArrayListPratice(){
data = new String[10];
//自定义容量大小
public ArrayListPratice(int r){
if (r < 0)
throw new IllegalArgumentException();
data = new String[r];
}
//扩容
public void grow(){
if (data.length <= 1)
Arrays.copyOf(data,data.length+1);
else
Arrays.copyOf(data,data.length+data.length>>1);
}
//增加元素
public void add(String str){
if (size >= data.length)
grow();
data[size++] = str;
}
//查找元素第一次出现的位置
public int indexOf(String str){
for (int i = 0;i<size;i++){
if (data[i]==str || data[i] == null && data[i].equals(str))
return i;
}
return -1;
}
//在指定索引处增加元素
public void add(String str,int index){
out(index);
if (data.length <= size)
grow();
System.arraycopy(data,index,data,index+1,size - index);
data[index] = str;
size++;
}
//删除指定索引处的元素
public void remove(int index){
if (index < 0 || index >= size)
throw new ArrayIndexOutOfBoundsException();
System.arraycopy(data,index+1,data,index,size-index-1);
size--;
}
//删除指定元素
public void remove(String str){
int index = indexOf(str);
remove(index);
}
//判断是否包含某元素
public boolean contains(String str){
if (indexOf(str) == -1)
return false;
return true;
}
//获得该索引处的元素
public String get(int i){
return data[i];
}
//判断集合是否为空
public boolean isEmpty(){
return size==0;
}
//清空集合
public void clear(){
data = new String[10];
size = 0;
}
//修改某元素为某元素
public void set(String str1,String str2){
int i =indexOf(str1);
data[i] = str2;
}
//修改某索引处的元素
public void set(int index,String str){
out(index);
data[index] = str;
}
//抛出异常集合
private void out(int index) {
if (index < 0 || index > size)
throw new ArrayIndexOutOfBoundsException();
}
//元素截取
public ArrayListPratice sublist(int fromIndex,int toIndex){
this.out(fromIndex);
this.out(toIndex);
if (fromIndex > toIndex)
throw new ArrayIndexOutOfBoundsException();
ArrayListPratice sublist = new ArrayListPratice(toIndex-fromIndex);
sublist.size = toIndex - fromIndex;
System.arraycopy(data,fromIndex,sublist.data,0,toIndex-fromIndex);
return sublist;
}
}