import java
.util
.Arrays
;
class MyArrayList {
private int[] elem
;
private int usedSize
;
private final int CAPACITY
= 5;
public MyArrayList() {
this.elem
= new int[CAPACITY
];
this.usedSize
= 0;
}
public void display() {
for (int i
= 0; i
< this.usedSize
; i
++) {
System
.out
.print(this.elem
[i
] + " ");
}
System
.out
.println();
}
private boolean isfull() {
return this.elem
.length
== this.usedSize
;
}
public void add(int pos
, int data
) {
if (isfull()) {
this.elem
= Arrays
.copyOf(this.elem
, this.elem
.length
* 2);
}
if (pos
< 0 || pos
> this.usedSize
) {
System
.out
.println("该位置不合法");
}
for (int i
= this.usedSize
- 1; i
>= pos
; i
--) {
this.elem
[i
+ 1] = this.elem
[i
];
}
this.elem
[pos
] = data
;
this.usedSize
++;
}
public boolean contains(int toFind
) {
for (int i
= this.usedSize
; i
>= 0; i
--) {
if (toFind
== this.elem
[i
]) {
return true;
}
}
return false;
}
public int search(int toFind
) {
for (int i
= 0; i
< this.usedSize
; i
++) {
if (this.elem
[i
] == toFind
) {
return i
;
}
}
return -1;
}
public int getPos(int pos
) {
if (pos
< 0 || pos
> usedSize
) {
return -1;
}
return this.elem
[pos
];
}
public void setPos(int pos
, int value
) {
this.elem
[pos
] = value
;
}
public void remove(int toremove
) {
int a
= search(toremove
);
if (a
== -1) {
System
.out
.println("找不到要删除的数字");
}
for (int i
= a
; i
< this.usedSize
- 1; i
++) {
this.elem
[i
] = this.elem
[i
+ 1];
}
this.usedSize
--;
}
public int size() {
return this.usedSize
;
}
public void clear() {
this.usedSize
= 0;
}
}
public class Test2 {
public static void main(String
[] args
) {
MyArrayList myArrayList
= new MyArrayList();
myArrayList
.add(0,12);
myArrayList
.add(1,23);
myArrayList
.add(2,34);
myArrayList
.add(3,45);
myArrayList
.add(4,56);
int sum
= myArrayList
.search(90);
System
.out
.println(sum
);
myArrayList
.remove(23);
myArrayList
.display();
int L
= myArrayList
.size();
System
.out
.println(L
);
myArrayList
.clear();
myArrayList
.display();
}
}
==========================================
输出结果:
-1
12 34 45 56
4
转载请注明原文地址: https://mac.8miu.com/read-495299.html