public class test8 { public static void main(String[] args) { test81 my = new test81(); my.add(0,10); my.add(1,20); my.add(2,30); my.add(3,40); my.add(6,50); my.display(); } }
1 import javax.xml.bind.annotation.XmlType; 2 3 public class test81 { 4 public int[] elem; 5 public int usedSize; 6 7 public static final int DEFAULT_SIZE = 10;//设置默认容量 8 public test81 () { 9 this.elem = new int[DEFAULT_SIZE]; 10 this.usedSize = 0; 11 } 12 //打印顺序列表 13 public void display() { 14 for (int i = 0; i < usedSize; i++) { 15 System.out.println(this.elem[i] + " "); 16 } 17 System.out.println(); 18 } 19 // 在 pos 位置新增元素 20 public void add(int pos, int data) { 21 if (isFull()) { 22 System.out.println("顺序表已经满了"); 23 return; 24 } 25 if(pos<0 || pos>usedSize){ 26 System.out.println("pos位置不合法"); 27 } 28 else { 29 for (int i = this.usedSize-1; i > pos ; i--) { 30 this.elem[i+1] = this.elem[i]; 31 } 32 this.elem[pos] = data; 33 this.usedSize++; 34 } 35 } 36 public boolean isFull() { 37 if(usedSize == this.elem.length) { 38 return true; 39 } 40 return false; 41 } 42 }
原文:https://www.cnblogs.com/Leafbud/p/12926268.html