|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 爱学习520 于 2022-3-30 20:50 编辑
报错是这样的,图片在最后
代码
- package cn.nw.algorithm.linear;
- import cn.nw.algorithm.linear.SequenceList;
- public class Test_linear {
- public static void main(String[] args) {
- SequenceList<int> l=new SequenceList<>();
- l.InSert(1,4);
- l.InSert(2,5);
- l.InSert(3,6);
- l.InSert(4,7);
- l.InSert(5,8);
- }
- }
- package cn.nw.algorithm.linear;
- public class SequenceList<T> {
- //成员变量
- private T[] eles;
- private int length;
- //无参构造方法,初始化默认大小为10
- public SequenceList(){
- this.eles=(T[]) new Object[10];
- this.length=0;
- }
- //无参构造方法
- public SequenceList(int capacity){
- //判断输入的capacity是否合法
- if(capacity<=0){
- System.out.print("error");
- System.exit(1);
- }
- this.eles=(T[]) new Object[capacity];
- this.length=0;
- }
- //在第i处插入一个元素
- public boolean InSert(int pos,T obj){
- //判断插入位置是否合法
- if(pos<1||pos>this.length+1){
- System.out.print("插入位置不合法");
- return false;
- }
- //如果插入时容量已满,扩容到当前长度的2倍
- if(this.length==eles.length){
- //定义一个临时数组temp保存原数组eles
- T[] temp=eles;
- //将现有的容量扩充为原来的2倍
- this.eles=(T[]) new Object[this.length*2];
- //将原有的数据依次拷贝到新数组
- for(int i=0;i<this.length;i++)
- this.eles[i]=temp[i];
- }
- //插入操作,所有的数据向下移动,直到腾出一个位置
- for(int i=this.length;i>=pos;i--)
- this.eles[i]=this.eles[i-1];
- //插入对应的元素
- this.eles[pos-1]=obj;
- //该数组长度加一
- this.length++;
- return true;
- }
- }
复制代码
本帖最后由 临时号 于 2022-5-20 23:26 编辑
第六行的int是一个基本数据类型,这个泛型数据类型中的<>中要求填类,可以将int换成Integer
如: - SequenceList<Integer> l=new SequenceList<Integer>();
复制代码
|
-
|