(Java)在數組的第i個座標下中插入一個數據元素,並保持數組元素的連續性

 1 package javaproject;
 2 public class Test 
 3 {
 4     public int[] insert(int[] a,int i,int data)
 5     {
 6             int len=a.length;    
 7             int[] temp=new int[len+1];
 8             for(int t=0;t<len;t++)
 9                 temp[t]=a[t];
10             if(i<0||i>len)
11                 return a;
12             else
13             {    
14                 try
15                 {
16                 for(int j=len;j>i;j--)
17                 {
18                     temp[j]=temp[j-1];
19                 }
20                 temp[i]=data;
21                 }
22                 catch(ArrayIndexOutOfBoundsException e )
23                 {
24                     System.out.println("數組越界");
25                 }
26                 return temp;
27             }        
28     }
29         public static void main(String [] args)
30         {
31             // TODO Auto-generated method stub
32             Test b = new Test();
33             int a1[]={1,2,3,5,6,7};
34             try{
35             System.out.println("array a:"+a1[0]+" "+a1[1]+" "+a1[2]+" "+a1[3]+" "+a1[4]+" "+a1[5]);
36             int temp[]=b.insert(a1, 3, 4);
37             System.out.println("插入4到a[3]:"+temp[0]+" "+temp[1]+" "+temp[2]+" "+temp[3]+" "+temp[4]+" "+temp[5]+" "+temp[6]);
38             }catch(ArrayIndexOutOfBoundsException e )
39             {
40                 System.out.println("數組越界");
41             }
42         }    
43 }
相關文章
相關標籤/搜索