如何根据以下顺序表,存放以下(3个)学生元素:姓名分数M170M280M396顺序表是按照分数从小到大排列的。本人java刚入门,不会用顺序表,希望有大神帮我写一下程序代码(多一点点注释)...
如何根据以下顺序表,存放以下(3个)学生元素:
姓名 分数
M1 70
M2 80
M3 96
顺序表是按照分数从小到大排列的。本人java刚入门,不会用顺序表,希望有大神帮我写一下程序代码(多一点点注释),感激不尽!
import java.lang.reflect.Array;
interface ILinarList {
boolean add(E item); //添加元素
boolean add(int index, E item);//插入元素
E remove(int index); //删除元素
int indexOf(E item); //定位元素
E get(int index); //取表元素
int size(); //求线性表长度
void clear();//清空线性表
boolean isEmpty(); //判断线性表是否为空
}
public class SeqList implements ILinarList {
private int maxsize; // 顺序表的最大容量
private E[] data; // 数组,用于存储顺序表中的数据元素
private int size; // 顺序表的实际长度
// 初始化线性表
@SuppressWarnings("unchecked")
public SeqList(Class type, int maxsize) {
this.maxsize = maxsize;
data = (E[]) Array.newInstance(type, maxsize);
size = 0;
}
// 添加元素,将元素添加在顺序表的末尾
public boolean add(E item) {
if (!isFull()) {
data[size++] = item;
return true;
} else
return false;
}
// 插入元素,将元素添加在顺序表指定的位置
public boolean add(int index, E item) {
if (index < 0 || index > size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: "+ size);
if (!isFull()) {
for (int j = size - 1; j >= index; j--) {
data[j + 1] = data[j];
}
data[index] = item;
size++;
return true;
} else
return false;
}
// 删除元素,删除顺序表的第i个数据元素
public E remove(int index) {
rangeCheck(index);
if (!isEmpty()) {
E oldValue = data[index];
for (int j = index; j < size-1; j++) {
data[j] = data[j+1];
}
data[--size] = null;// 清除最后一个元素
return oldValue;
} else
return null;
}
// 定位元素,返回对象item在顺序表中首先出现的索引位置,不存在item,则返回-1
public int indexOf(E item) {
if (item == null) {
for (int i = 0; i < size; i++)
if (data[i] == null)
return i;
} else {
for (int i = 0; i < size; i++)
if (item.equals(data[i]))
return i;
}
return -1;
}
// 取表元素,返回顺序表中指定索引位置index处的数据元素
public E get(int index) {
rangeCheck(index);
return data[index];
}
// 求顺序表长度
public int size() {
return size;
}
// 清空顺序表
public void clear() {
for (int i = 0; i < size; i++)
data[i] = null;
size = 0;
}
// 判断顺序表是否为空
public boolean isEmpty() {
return size == 0;
}
// 判断给定的索引号是否在指定的范围,如果不在,抛出索引越界异常
private void rangeCheck(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Index: " + index + ", Size: "
+ size);
}
// 判断顺序表是否为满
public boolean isFull() {
if (size == maxsize) {
return true;
} else {
return false;
}
}
}
展开