part1数组拼接
public class
ArrayTest
{
public static void
main
(
String
[]
args
){
//
原数组 长度为
5
只能存储
5
个元素
int
[]
arr
=
new int
[
5
];
//
通过
5
次循环将原数组中的空间占满
for
(
int
i
=
0
;
i
<
5
;
i
++
){
arr
[
i
]
=
i
;
}
//
创建一个更大的数组 将原数组的元素移动过来,将需要添加的新数组存储进入
int
[]
arr2
=
new int
[
10
];//(java中的数组定义)
for
(
int
i
=
0
;
i
<
5
;
i
++
){
arr2
[
i
]
=
arr
[
i
];
}
for
(
int
i
=
5
;
i
<
10
;
i
++
){
arr2
[
i
]
=
i
;
}
for
(
int
i
=
0
;
i
<
10
;
i
++
){
System
.
out
.
print
(
arr2
[
i
]
+
" "
);
}
}
}
part2扩容
public class
MyArray
{
//
什么类型的数据都可以存的数组
Object
[]
values
;//object所有数据类型
int
size
;
//
作为元素个数
/
作为下次存储元素的下标
int
length
;
static final int
initCap
=
10
;//final定义常量
//
构造方法:
public
MyArray
(){//public针对全局
length
=
initCap
;
values
=
new
Object
[
length
];
size
=
0
;
}
public
MyArray
(
int
initLength
){
if
(
initLength
<
2
){
System
.
out
.
println
(
"
输入的初始长度不能小于
2,
数组会使用默认的初始数据进行初始
化
"
);
length
=
initCap
;
values
=
new
Object
[
length
];
size
=
0
;
}
else
{
length
=
initLength
;
//
使用传入的参数进行初始化
values
=
new
Object
[
length
];
size
=
0
;
}
}
public void
add
(
Object
e
){//object为数据类型,e是对象
//
扩容
if
(
size
==
length
){
//
数组已经存满了 需要扩容的
int
oldLength
=
length
;
int
newLength
=
oldLength
+
(
oldLength
>>
1
);
// 1.5
倍,》1相当于除以2
// System.out.println (newLength);
//
使用新的长度创建一个新的 容量更大的数组
Object
[]
newValues
=
new
Object
[
newLength
];
//
将原数组中的元素
i
移动到新数组中
for
(
int
i
=
0
;
i
<
oldLength
;
i
++
){
newValues
[
i
]
=
values
[
i
];
}
//
将新数组的对象变量名中存储的新数组的内存地址赋值给旧数组名
values
=
newValues
;
//
更新最新的数组长度,引用传递
length
=
newLength
;
System
.
out
.
println
(
"
数组扩容完成,长度是:
"
+
length
);
}
主函数
public static void
main
(
String
[]
args
){
MyArray
myArray
=
new
MyArray
(
10
);
for
(
int
i
=
0
;
i
<
30
;
i
++
){
myArray
.
add
(
"hello"
+
i
);
}
part3根据下标获取元素
public void
addAll
(
Object
[]
eArr
){
}
//
根据传入的下标获取数组元素
public
Object get
(
int
index
){
//
检查传入的下标是否在合法的区间内 (
0~size-1)
if
(
index
>=
0
&&
index
<
size
){
Object
e
=
values
[
index
];
return
e
;
}
System
.
out
.
println
(
"
传入的下标不在数组的范围内
~"
);
return null
;
}
//
替换传入下标位置的元素
public void
set
(
int
index
,
Object
e
){
}
//
根据下标移除元素 并且返回被移除的元素
//
被移除的元素所在的位置,需要后置数据前移填充
public
Object remove
(
int
index
){
if
(
index
>=
0
&&
index
<
size
){
Object
oldE
=
values
[
index
];
for
(
int
i
=
index
;
i
<
size
-
1
;
i
++
){
values
[
i
]
=
values
[
i
+
1
];
}
size
--
;
return
oldE
;
}
System
.
out
.
println
(
"
传入的下标不在数组的范围内
~"
);
return null
;
}
public
String toString
(){
String
str
=
"{"
;
for
(
int
i
=
0
;
i
<
size
;
i
++
){
str
+=
values
[
i
]
+
","
;
}
str
+=
"}"
;
return
str
;
}
public static void
main
(
String
[]
args
){
MyArray
myArray
=
new
MyArray
(
10
);
for
(
int
i
=
0
;
i
<
30
;
i
++
){
myArray
.
add
(
"hello"
+
i
);
}
System
.
out
.
println
(
myArray
.
toString
());
myArray
.
remove
(
5
);
myArray
.
remove
(
10
);
System
.
out
.
println
(
myArray
.
toString
());
// for(int i = 100; i < 5000; i++){
// myArray.add ("hello" + i);
//
// }
//
// System.out.println (myArray.get (450));
// System.out.println (myArray.get (5020));