数组基础
- 把数据码成一排进行存放
索引可以有语义也可以没有语义
我们先来看一个简单的数组
package arithmetic;
public class main {
public static void main(String[] args) {
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i;
}
int[] scores = new int[]{100,99,98};
for (int i=0;i<scores.length;i++){
System.out.println(scores[i]);
}
for(int score : scores){
System.out.println(score);
}
}
}
相信大家对上面这段代码在了解不过了。
- 数组最大的优点:快速查询
- 数组最好应用于“索引有语义”的情况
- 但并非所有有语义的所有都适用于数组
比如:身份证号:10101010181829182 - 这里我们主要处理“索引没有语义”的情况数组的使用
制作属于我们自己的数组类
- 索引没有语义,如何表示没有元素?
- 如何添加元素?如何删除元素?
- 。。。。
- 基于java的数组,二次封装属于我们自己的数组类
增 删 改 查
capacity(容量),size(大小)
看下面代码?
package arithmetic;
public class Array {
private int[] data;
private int size;
//构造函数,传入数组的容量capacity构造Array
public Array(int capacity) {
data = new int[capacity];
size = 0;
}
//无参构造函数,默认数组的容量capa=10
public Array() {
this(10);
}
//获取数组中的元素个数
public int geySiaze() {
return size;
}
//获取数组的容量
public int getCapacity() {
return data.length;
}
public boolean isEmpty() {
return size == 0;
}
//获取数组容量
public void addLast(int e) {
// if (size == data.length)
// throw new IllegalArgumentException("AddLast failed.Array is full");
// data[size] = e;
// size++;
//有了add方法就不需要在写上面的代码了
add(size, e);
}
public void addFirst(int e) {
//有了add方法就直接调用就行了
add(0, e);
}
//在第index个位置插入一个新元素e
public void add(int index, int e) {
if (size == data.length)
throw new IllegalArgumentException("Add failed . Array is full");
if (index < 0 || index > size)
throw new IllegalArgumentException("add failed .Require index > 0 and index < size ");
for (int i = size - 1; i >= index; i--)
data[i + 1] = data[i];
data[index] = e;
size++;
}
//获取第index个元素
int get(int index) {
if (index < 0 || index >= size)
throw new IllegalArgumentException("get failed ,index is