JAVA顺序表求表长_java:如何根据顺序表定义一个可以存放3个学生元素的顺序表(含有顺序表完整代码)。...

如何根据以下顺序表,存放以下(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;

}

}

}

展开

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值