顺序表JAVA代码
2024-08-30 18:10:12
publicclassSeqList{
final int defaultSize =10; //默认的顺序表的最大长度
int maxSize; //最大长度
int size; //当前长度
Object[] listArray; //对象数组
publicSeqList(){
init(defaultSize);
}
publicSeqList(int size){
init(size);
}
//顺序表的初始化方法
privatevoid init(int size){
maxSize = size;
this.size =0;
listArray =newObject[size];
}
publicvoiddelete(int index) throws Exception
{
//容错性
if(isEmpty()){
thrownewException("顺序表为空,无法删除!");
}
if(index <0|| index > size -1){
thrownewException("参数错误!");
}
//移动元素(从前往后操作)
for(int j = index; j < size -1; j++)
listArray[j]= listArray[j +1];
listArray[size -1]= null; //注意释放内存(避免内存泄漏)
size--;
}
publicObject get(int index) throws Exception
{
if(index <0|| index >= size){
thrownewException("参数错误!");
}
return listArray[index];
}
publicvoid insert(int index,Object obj) throws Exception
{
//容错性
if(size == maxSize){
thrownewException("顺序表已满,无法插入!");
}
if(index <0|| index > size){
thrownewException("参数错误!");
}
//移动元素(从后往前操作)
for(int j = size -1; j >= index; j--)
listArray[j +1]= listArray[j];
listArray[index]= obj;
size++;
}
public boolean isEmpty(){
return size ==0;
}
publicint size(){
return size;
}
}
publicclassTest{
publicstaticvoid main(String[] args){
SequenceListlist=newSequenceList(20);
try{
list.insert(0,100);
list.insert(0,50);
list.insert(1,20);
for(int i =0; i <list.size; i++){
System.out.println("第"+ i +"个数为"+list.get(i));
}
}catch(Exception e){
e.printStackTrace();
}
}
}
最新文章
- 在ESXi 5.x 和 ESXi 6.0.x 中如何安装第三方供应商开发的驱动程序
- spread 程序调试时,未激活的提示解决
- POJ 1258 Agri-Net(最小生成树 Prim+Kruskal)
- Java基础类型与其二进制表示
- xctest错误问题解决
- sql语句延时执行或者是指定时间执行
- Cocos2d-android (05) 渐变动画(颜色,淡入淡出。。。)
- 修改的某人的SqlHelper FOR ODBC
- live555源码研究(一)------live555MediaServer的启动过程和基本类图
- 【matlab】matalb生成dll给Cpp用
- Activity的学习
- centos无法载入 mcrypt 扩展,<;br />;请检查 PHP 配置,经过各种尝试,终于找到了解决办法
- AutoMapper使用简单总结
- 桥接模式和nat模式的区别
- c/c++ 线性表之顺序表
- JavaWeb学习 (十七)————JSP属性范围
- Justified Jungle
- 关于<;asp:checkBoxList>;控件的对齐方法
- BZOJ4078 WF2014Metal Processing Plant(二分答案+2-SAT)
- centos7下安装nginx(转)