forked from fantj2016/Java-dataStruct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMyArray.java
More file actions
89 lines (83 loc) · 1.85 KB
/
MyArray.java
File metadata and controls
89 lines (83 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.fantj.dataStruct.array;
/**
* Created by Fant.J.
* 2017/12/20 18:16
*/
public class MyArray {
private long[] arr;
//表示有效数据的长度
private int elements;
public MyArray() {
arr = new long[50];
}
public MyArray(int maxsize) {
arr = new long[maxsize];
}
/**
* 添加数据
*/
public void insert(long value){
arr[elements] = value;
elements++;
}
/**
* 显示数据
*/
public void display(){
System.out.print("[");
for (int i = 0;i < elements;i++){
System.out.print(arr[i]+" ");
}
System.out.print("]");
}
/**
* 查找数据(根据元素查找)
*/
public int search(long value){
int i;
for (i = 0;i < elements;i++){
if (value == arr[i]){
break;
}
}
//是否查到最后一个了
if (i == elements){
return -1; //查找不到
}else {
return i;
}
}
/**
* 根据索引查找
*/
public long get(int index){
if (index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
}else {
return arr[index];
}
}
/**
* 删除数据
*/
public void delete(int index){
if (index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
}else {
for (int i = index;i < elements;i++){
arr[index] = arr[index+1];
}
elements--;
}
}
/**
* 更新数据
*/
public void update(int index,long newvalue){
if (index >= elements || index < 0){
throw new ArrayIndexOutOfBoundsException();
}else {
arr[index] = newvalue;
}
}
}