Java实例03-超级数组
写一个具有增删查改功能的超级数组类
主类(实现增删查改):
package com.tsccg; /** * @author: TSCCG * @date: 2021/5/18 */ public class SuperArray { private Object[] arr; private int currentIndex = -1; public SuperArray(int size) { arr = new Object[size]; } /** * 定义数组默认长度为10 */ public SuperArray() { this(10); } /** * 1.增加数据 */ public void add(Object data) { currentIndex++; if (currentIndex >= arr.length) { Object[] newArr = new Object[currentIndex * 2]; for (int j = 0; j < arr.length; j++) { newArr[j] = arr[j]; } arr = newArr; } arr[currentIndex] = data; } /** * 2.删除某个数据 */ public void delete(int index) { if (index < 0 || index > currentIndex) { System.out.println("数组中没有这个元素!"); } else { for (int i = index; i < currentIndex; i++) { arr[i] = arr[i + 1]; } currentIndex--; } } /** * 3.通过下标查询某个数据 * @return */ public Object get(int index) { return (Object)arr[index]; } /** * 4.修改数据 */ public void update(int index, Object newValue) { arr[index] = newValue; } /** * 5.输出数据 */ public void print() { for (int i = 0; i <= currentIndex; i++) { if (i == currentIndex) { System.out.println(arr[i]); } else { System.out.print(arr[i] + " "); } } } /** * 6.打印长度 */ public int size() { return currentIndex + 1; } }
package com.tsccg; /** * @author: TSCCG * @date: 2021/5/14 */ public class Test { public static void main(String[] args) { SuperArray su = new SuperArray(); su.add(4); su.add(1); su.add(3); su.add(2); System.out.println("添加:"); su.print(); su.delete(3); System.out.println("删除:"); su.print(); System.out.println("查找:"); System.out.println(su.get(1)); su.update(1,8); System.out.println("改:"); su.print(); } }
添加: 4 1 3 2 删除: 4 1 3 查找: 1 改: 4 8 3