数组
来源:互联网 发布:十大神优化游戏 编辑:程序博客网 时间:2024/05/15 20:25
原文地址:http://www.tianshouzhi.com/api/tutorials/basicalgorithm/321
上面博客的Array因为capacity和size不明确,导致Array有问题,下面是更改后的Array:
public class Array<V> { private Object[] elements; // 对象数组 private int size = 0; // 数组中实际元素的数量,1,2,3,并非index private int capacity; // 数组容量 /** * 构造函数 * @param capacity */ public Array(int capacity){ this.capacity = capacity; if(capacity <= 0){ throw new IllegalArgumentException("capacity must > 0"); } elements = new Object[capacity]; } /** * 添加 * @param v */ public void insert(V v){ // 到达容量限制 if(size == capacity){ throw new IndexOutOfBoundsException(); } elements[size] = v; size++; // 实际数量+1 } /** * 移除 * @return */ public boolean remove(V v){ for(int i = 0; i < size; i++){ if(v.equals(elements[i])){ elements[i] = null; // 删除 moveUp(i, size); // 将后面的所有元素都往前移动一个位置 size--; // 实际数量-1 return true; } } return false; // 没有匹配元素则返回false } /** * 查找指定元素 * 有,返回对应元素,没有返回null * @param v * @return */ public V find(V v){ for(int i = 0; i < size; i++){ if(v.equals(elements[i])){ return (V) elements[i]; } } return null; } /** * 根据下表返回元素 * @param index * @return */ public V get(int index){ if(index > capacity -1){ // 越界 throw new IndexOutOfBoundsException(); } return (V) elements[index]; } /** * 将后面的所有元素都往前移动一个位置 * @param i 当前位置index * @param size 当前数组大小 */ public void moveUp(int i, int size){ while(i < size -1){ elements[i] = elements[++i]; } elements[size-1] = null; // 最后一个位置null } /** * 返回数组元素中的数量 * @return */ public int size(){ return size(); } /** * 打印数组 * @param prefix */ public void display(String prefix) { System.out.print(prefix); for (int i = 0; i < elements.length; i++) { if (i < size) { System.out.print(elements[i] + " "); }else{ System.out.print("null" + " "); } } System.out.println(); } public static void main(String[] args) { Array<Integer> array=new Array<Integer>(5); array.insert(1); array.insert(2); array.insert(3); array.insert(4); array.display("初始 1,2,3,4 : "); array.insert(5); array.display("添加 5 : "); array.remove(3); array.display("删除 3 : "); System.out.println("查找 4:"+array.find(4) ); System.out.println("查找 3:"+array.find(3) ); }}
阅读全文
0 0
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 数组
- 如何使用区块链技术进行项目开发
- Android源代码编译命令m/mm/mmm/make分析
- 【SequoiaDB教程】SequoiaDB分布式存储教程
- 算法大赛打响反击今日头条的第一枪
- 简单封装自定义MVC框架
- 数组
- 异常
- C# Is AS 的区别
- Voice Conversion 项目笔记(含从VCC 2016匿名比赛深挖的各前沿方法性能对比)
- redis-sentinel安装配置
- React前端开发入门与实战案例
- nginx限流方案
- [Android] ProgressDialog与耗时操作
- C++ 左值和右值,左值引用和右值引用