目录
一、ArrayList的遍历
ArrayList的遍历有三种,分别为for循环+下标、foreach、迭代器,使用方法如下:
public static void main(String[] args) {
ArrayList<Integer> arraylist=new ArrayList<>();
arraylist.add(1);
arraylist.add(2);
arraylist.add(3);
arraylist.add(4);
//遍历方式
//第一种
for(int i=0;i< arraylist.size();i++){
System.out.print(arraylist.get(i)+" ");
}
System.out.println();
//第二种
System.out.println("================第二种====================");
for (Integer integer:arraylist
) {
System.out.print(integer+" ");
}
System.out.println();
//第三种
System.out.println("================第三种====================");
Iterator<Integer> iterator=arraylist.iterator();
while(iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
}
运行结果为:
二、ArrayList的扩容
1.预估扩容的大小
(1)初步扩容按照1.5倍大小扩容;
(2)如果用户所需大小超过预估1.5倍大小,则按照用户所需大小扩容。
2.使用copyOf进行扩容
三、ArrayList简单模拟实现
public class MyArrayList {
public int[] array;
public int UsedSize;
//构造方法
public MyArrayList() {
this.array =new int[10];
}
// 打印顺序表
public void myToString() {
for(int i=0;i<this.UsedSize;i++){
System.out.print(this.array[i]+" ");
}
System.out.println();
}
// 新增元素,默认在数组最后新增
public void add(int data) {
if(isFull()) {
//扩容
this.array=Arrays.copyOf(this.array,this.array.length*2);
}
this.array[this.UsedSize] = data;
this.UsedSize++;
}
public boolean isFull(){
if (this.UsedSize==this.array.length){
return true;
}
return false;
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(pos<0||pos>this.UsedSize){
System.out.println("pos位置不合法");
return;
}
//1.不能是满的
if(isFull()) {
//扩容
this.array=Arrays.copyOf(this.array,this.array.length*2);
}
for(int i=this.UsedSize;i>=pos;i--){
this.array[i+1]=this.array[i];
}
this.array[pos]=data;
this.UsedSize++;
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for(int i=0;i<this.UsedSize;i++){
if(array[i]==toFind){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int indexOf(int toFind) {
for(int i=0;i<this.UsedSize;i++){
if(array[i]==toFind){
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int get(int pos) {
if(pos<0||pos>this.UsedSize) {
System.out.println("pos位置不合法");
return -1;
}
return this.array[pos];
}
// 给 pos 位置的元素设为 value
public void set(int pos, int value) {
if(pos<0||pos>this.UsedSize) {
System.out.println("pos位置不合法");
return;
}
this.array[pos]=value;
}
//删除第一次出现的关键字key
public void remove(int toRemove) {
if(isEmpty()){
return;
}
int k=-1;
//判断是否包含关键字
for(int i=0;i<this.UsedSize;i++){
if(array[i]==toRemove){
k=i;
break;
}
}
if(k==-1){
System.out.println("没有该关键字!");
return;
}
for(int i=k;i<this.UsedSize-1;i++){
array[i]=array[i+1];
}
this.UsedSize--;
}
public boolean isEmpty(){
if(this.UsedSize==0){
return false;
}
return true;
}
// 获取顺序表长度
public int size() {
return this.UsedSize;
}
// 清空顺序表
public void clear() {
//简单类型
this.UsedSize=0;
/*
引用类型
for(int i=0;i<this.UsedSize;i++){
array[i]=null;
}
this.UsedSize=0;
*/
}
}