顺序表的实现
程序员文章站
2022-03-21 11:07:49
...
顺序表的初始化、和基本操作的实现(插入、删除、按值查找)
问题:
1、顺序表的位序和数组下标的区别
2、throw抛出异常
3、to string的重要性
package array; public class shunxu<T> { private int maxSize=50; private int capacity; private Object[] elementdata; private int size; public shunxu(){ capacity=maxSize; this.elementdata=new Object[capacity]; size=0; } public int length(){ return size; } //获取顺序表中索引为i的元素 public T get(int i){ if(i<0||i>size-1){ throw new IndexOutOfBoundsException("线性表索引越界"); } return (T)elementdata[i]; } //在末尾添加元素 public void add(T element){ if(size>=maxSize){ throw new IndexOutOfBoundsException("线性表已满"); } elementdata[size]=element; size++; } //向顺序表的指定位置插入一个元素 private void insert(T element, int index) { // TODO Auto-generated method stub if(index<0||index>size){ throw new IndexOutOfBoundsException("线性表越界"); } if(size>=maxSize){ throw new IndexOutOfBoundsException("线性表已满"); }else{ for(int j=size-1;j>=index;j--){ elementdata[j+1]=elementdata[j]; } elementdata[index]=element; } size++; } //删除第i个元素 public void delete(int index){ if(index<0||index>size){ throw new IndexOutOfBoundsException("线性表越界"); } if(size>=maxSize){ throw new IndexOutOfBoundsException("线性表已满"); }else{ for(int j=index;j<=size;j++){ elementdata[j]=elementdata[j+1]; } size--; } } //查找元素值等于a的元素,并返回其位序 public int locate(T element){ for(int i=0;i<size;i++){ if(elementdata[i].equals(element)){ return i; } } return -1; } public String toString() { if (size == 0) { return "[]"; } else { StringBuilder sb = new StringBuilder("["); for (int i = 0 ; i < size ; i++ ) { sb.append(elementdata[i].toString() + ", "); } int size = sb.length(); return sb.delete(size - 2 , size).append("]").toString(); } } public static void main(String[] args) { // TODO Auto-generated method stub shunxu list=new shunxu(); list.add("aa"); list.add(2); list.add(3); list.insert("royal", 2); list.delete(2); System.out.println(list.locate(2)); System.out.println(list); }