1. 自定义数组的二次封装
主要想实现的功能:
- boolean isEmpty();
- E get(int index) // 查找索引对应的元素e
- E set( int index, E e) //修改index索引位置的元素e
- boolean contains(E e) //查找数组中是否有元素e
- int find(E e) //查找元素e对应的索引位置,如果不存在元素返回-1
- add( E e)系列
- remove(E e)系列
实现代码如下:
public class Array<E> {
//在自己封装的类中,成员变量最好都是私有的,其它人只能通过方法来获取成员信息。
private E[] data;
private int size;
/**
*传入数组的容量构造Array
* @param capacity
*/
public Array(int capacity){
data = (E[])new Object[capacity];
size = 0;
}
//无参构造函数,默认初始容量是10
public Array(){
this(10);//逻辑上声明一个初始值
}
//1.获取数组的元素个数或容量
public int getSize(){ return size; }
public int getCapacity(){ return data.length;}
//2.数组判空
public boolean isEmpty(){return size==0;}
//3.获取某索引对应元素
public E get(int index) {
return data[index];
}
//4.获取元素对应的索引位置
public int find(E e){
for(int i=0; i<size; i++){
if(data[i].equals(e)) return i;
}
return -1;
}
//5.判断元素存在
public boolean contains(E e){
for(int i=0; i<size; i++) {
if (data[i].equals(e)) return true;
}
return false;
}
//6.添加元素系列
public void add(int index, E 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");
for(int i = size-1; i>=index; i--) {data[i+1] = data[i];}
data[index] = e;
size++;
}
public void addLast(E e){
add(size, e);
}
public void addFirst(E e){
add(0,e);
}
//7.删除元素系列
public E remove(int index){
if(index<0 || index>size)
throw new IllegalArgumentException("Remove failed. Index is Illegal");
E ret = data[index];
for(int i=index+1; i<size; i++){ data[i-1] = data[i]; }
size--;
return ret;
}
public E removeFirst(){
return remove(0);
}
public E removeLast(){
return remove(size-1);
}
//注意:已经制定了要删除的元素,就不需要索引了
public void removeElement(E e){
int index = find(e);
if(index!=-1) remove(index);
}
}
2. 数组功能
1.找出数组中的最大值
double max = arr[0];
for(int i; i<arr.length; i++){
if(arr[i]>max) max = arr[i];
}
2.复制数组
int N = arr.length
double[] b = new double[N];
for(int i=0; i<N; i++) {
for(int i=0; i<N; i++) b[i] = a[i];
}
3.颠倒数组元素的顺序
int N = arr.length
for(int i=0; i<N; i++) {
for(int i=0; i<N/2; i++)
int tmp = arr[N-1-i];
arr[N-1-i] = arr[i];
arr[i] = tmp;
}
3. 使用泛型
-
让自己的数据结构可以“任意地”放数据类型(不可以放基本数据类型,只能是类对象)
-
每个基本数据类型都有一个对应的包装类,这样就方便使用泛型了
boolean, byte, char, short, int, long, float, double
Boolean, Byte, Char, Short, Int, Long, Float, Double