/**
* @Description: 自定义数组
* @Date 2018/12/22 17:28
* @Version 1.0
**/
public
class
CustomArray<E> {
/**
* 数组
*/
private
E[] data;
/**
* 数组元素的个数
*/
private
int
size;
/**
* 指定大小的构造器
*/
public
CustomArray(
int
capacity){
if
(capacity >
0
) {
data = (E[])
new
Object[capacity];
size =
0
;
}
else
{
throw
new
IllegalArgumentException(
"Illegal Capacity: "
+ capacity);
}
}
/**
* 默认数组大小为10
*/
public
CustomArray(){
this
(
10
);
}
/**
* 获取元素的个数
*/
public
int
getSize(){
return
size;
}
/**
* 获取数组的容量
*/
public
int
getCapacity(){
return
data.length;
}
/**
* 数组元素是否为空
*/
public
boolean
isEmpty(){
return
size ==
0
;
}
/**
* 向数组末尾添加元素
*/
public
void
addLast(E e){
add(size,e);
}
/**
* 向数组第一位添加元素
*/
public
void
addFirst(E e){
add(
0
,e);
}
/**
* 在指定索引处添加元素
*/
public
void
add(
int
index,E e){
if
(size == data.length){
throw
new
IllegalArgumentException(
"Array space is exhausted"
);
}
if
(index <
0
|| index > data.length){
throw
new
ArrayIndexOutOfBoundsException(
"Array index out of range: "
+ index);
}
for
(
int
i=size -
1
;i >= index;i--){
data[i +
1
] = data[i];
}
data[index] = e;
size ++;
}
/**
* 获取指定索引处的值
*/
public
E get(
int
index){
if
(index <
0
|| index > data.length){
throw
new
ArrayIndexOutOfBoundsException(
"Array index out of range: "
+ index);
}
return
data[index];
}
/**
* 修改指定索引处的值
*/
public
void
set(
int
index,E e){
if
(index <
0
|| index > data.length){
throw
new
ArrayIndexOutOfBoundsException(
"Array index out of range: "
+ index);
}
data[index] = e;
}
/**
* 删除指定索引处的值
*/
public
void
remove(
int
index){
if
(index <
0
|| index > data.length){
throw
new
ArrayIndexOutOfBoundsException(
"Array index out of range: "
+ index);
}
for
(
int
i = index +
1
; i < size ; i++) {
data[i-
1
] = data[i ];
}
data[size -
1
] =
null
;
size --;
}
/**
* 删除某一个元素
*/
public
boolean
removeElement(E e){
int
i = find(e);
if
(i != -
1
){
remove(i);
return
true
;
}
return
false
;
}
/**
* 查询数组中是否包含某个值
* 包含返回true,否则返回false
*/
public
boolean
contains(E e){
for
(
int
i =
0
; i < data.length; i++) {
if
(data[i].equals(e)){
return
true
;
}
}
return
false
;
}
/**
* 查找指定内容的索引
* 如果未找到,返回-1
*/
public
int
find(E e){
for
(
int
i =
0
; i < data.length; i++) {
if
(data[i].equals(e)){
return
i;
}
}
return
-
1
;
}
/**
* 重写toString 方便打印
*/
@Override
public
String toString() {
StringBuilder sb =
new
StringBuilder();
sb.append(String.format(
"Array: size=%d ,capacity=%d \n"
,size,data.length));
sb.append(
"["
);
for
(
int
i=
0
;i<size;i++){
sb.append(data[i]);
if
(i != size -
1
){
sb.append(
" , "
);
}
}
sb.append(
"]"
);
return
sb.toString();
}
}