本篇文章主要是对数组的实操,所以对数组的概念不在赘述,了解更多数组相关可参照链接 Java数组的概念及使用-CSDN博客
1、DynamicArray类
package com.hh.algorithm.array;import java.util.Arrays;
import java.util.Iterator;
import java.util.function.Consumer;
import java.util.stream.IntStream;public class DynamicArray implements Iterable<Integer> {private int size = 0; //数组大小private int capacity = 8; //容量private int[] array = {};//添加元素到数组最后public void addLast(int element) {
// array[size] = element;
// size++;add(size, element);}//添加元素到数组指定索引为止public void add(int index, int element) {if (index > 0 && index < size) {System.arraycopy(array, index,array, index + 1, size - index);}array[index] = element;size++;}//指定索引查找public int get(int index) {return array[index];}//遍历方法一:Consumer遍历public void foreach(Consumer<Integer> consumer) {/*for (int i = 0; i < array.length; i++) {System.out.println(array[i]);}*/for (int i = 0; i < size; i++) {consumer.accept(array[i]);}}//遍历方法二:iterator迭代器遍历@Overridepublic Iterator<Integer> iterator() {return new Iterator<Integer>() {int i = 0;@Overridepublic boolean hasNext() {return i < size;}@Overridepublic Integer next() {return array[i++];}};}//遍历方法三:Consumer遍历public IntStream stream() {return IntStream.of(Arrays.copyOfRange(array, 0, size));}//删除索引元素public int remove(int index) {int remove = array[index];if (index < size - 1) {System.arraycopy(array, index + 1,array, index, size - index - 1);}size--;return remove;}//扩容数组public void checkAndGrew(int index) {//容量检测if (size == 0){array = new int[capacity];}else if (size == capacity){// 容量扩容,1.5,1.618,2倍capacity += capacity >> 1;int[] newArray = new int[capacity];System.arraycopy(array,0,newArray,0, size);array = newArray;}}
}
2、DynamicArrayTest测试类
package com.hh.algorithm.array;import org.testng.annotations.Test;import java.util.function.Consumer;public class DynamicArrayTest {//添加元素@Testpublic void test() {DynamicArray dynamicArray = new DynamicArray();dynamicArray.addLast(1);dynamicArray.addLast(2);dynamicArray.addLast(3);dynamicArray.addLast(4);dynamicArray.addLast(5);}//测试遍历@Testpublic void test1() {DynamicArray dynamicArray = new DynamicArray();dynamicArray.addLast(1);dynamicArray.addLast(2);dynamicArray.addLast(3);dynamicArray.addLast(4);dynamicArray.addLast(5);//方式一dynamicArray.get(1);//方式二dynamicArray.foreach(new Consumer<Integer>() {@Overridepublic void accept(Integer integer) {System.out.println(integer);}});//方式三for (Integer i : dynamicArray) { //自动执行hasNext和nextSystem.out.println(i);}//方式四dynamicArray.stream().forEach(element ->{System.out.println(element);});}
}
运行结果
本文为学习笔记,所参考文章均已附上链接,若有疑问请私信!
创作不易,如果对你有点帮助的话麻烦点个赞支持一下!
新手小白,欢迎留言指正!