设计一个javaMyVector类,表示向量
时间: 2024-05-20 16:17:37 浏览: 49
import java.util.Arrays;
public class MyVector {
private int[] data;
private int size;
public MyVector() {
data = new int[10];
size = 0;
}
public MyVector(int capacity) {
data = new int[capacity];
size = 0;
}
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public void add(int value) {
if (size == data.length) {
resize();
}
data[size++] = value;
}
public void add(int index, int value) {
if (index < 0 || index > size) {
throw new IndexOutOfBoundsException();
}
if (size == data.length) {
resize();
}
for (int i = size; i > index; i--) {
data[i] = data[i - 1];
}
data[index] = value;
size++;
}
public int get(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
return data[index];
}
public int set(int index, int value) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int old = data[index];
data[index] = value;
return old;
}
public int remove(int index) {
if (index < 0 || index >= size) {
throw new IndexOutOfBoundsException();
}
int value = data[index];
for (int i = index; i < size - 1; i++) {
data[i] = data[i + 1];
}
size--;
return value;
}
public boolean removeValue(int value) {
for (int i = 0; i < size; i++) {
if (data[i] == value) {
remove(i);
return true;
}
}
return false;
}
public void clear() {
size = 0;
}
public boolean contains(int value) {
for (int i = 0; i < size; i++) {
if (data[i] == value) {
return true;
}
}
return false;
}
public int indexOf(int value) {
for (int i = 0; i < size; i++) {
if (data[i] == value) {
return i;
}
}
return -1;
}
public int lastIndexOf(int value) {
for (int i = size - 1; i >= 0; i--) {
if (data[i] == value) {
return i;
}
}
return -1;
}
private void resize() {
int[] newData = new int[data.length * 2];
System.arraycopy(data, 0, newData, 0, size);
data = newData;
}
@Override
public String toString() {
int[] copy = Arrays.copyOf(data, size);
return Arrays.toString(copy);
}
}
阅读全文