//数组的用法:// "static void main" must be defined in a public class.publicclassMain{publicstaticvoidmain(String[] args){// 1. Initialize 初始化int[] a0 =newint[5];int[] a1 ={1,2,3};// 2. Get Length 得到长度
System.out.println("The size of a1 is: "+ a1.length);// 3. Access element 访问元素
System.out.println("The first element is: "+ a1[0]);// 4. Iterate all Elements 迭代所有元素
System.out.print("[Version 1] The contents of a1 are:");for(int i =0; i < a1.length;++i){
System.out.print(" "+ a1[i]);}
System.out.println();
System.out.print("[Version 2] The contents of a1 are:");for(int item: a1){
System.out.print(" "+ item);}
System.out.println();// 5. Modify Element 修改元素
a1[0]=4;// 6. Sort 分类
Arrays.sort(a1);}}
动态数组用法
//动态数组用法// "static void main" must be defined in a public class.publicclassMain{publicstaticvoidmain(String[] args){// 1. initialize 初始化
List<Integer> v0 =newArrayList<>();
List<Integer> v1;// v1 == null// 2. cast an array to a vector 将数组转换为向量
Integer[] a ={0,1,2,3,4};
v1 =newArrayList<>(Arrays.asList(a));// 3. copy
List<Integer> v2 = v1;// another reference to v1 对v1的另一个引用
List<Integer> v3 =newArrayList<>(v1);// make an actual copy of v1 制作v1的实际副本// 3. get length 得到长度
System.out.println("The size of v1 is: "+ v1.size());;// 4. access element 访问元素
System.out.println("The first element in v1 is: "+ v1.get(0));// 5.iterate the vector 迭代向量
System.out.print("[Version 1] The contents of v1 are:");for(int i =0; i < v1.size();++i){
System.out.print(" "+ v1.get(i));}
System.out.println();
System.out.print("[Version 2] The contents of v1 are:");for(int item : v1){
System.out.print(" "+ item);}
System.out.println();// 6. modify element 修改元素
v2.set(0,5);// modify v2 will actually modify v1 修改v2实际上会修改v1
System.out.println("The first element in v1 is: "+ v1.get(0));
v3.set(0,-1);
System.out.println("The first element in v1 is: "+ v1.get(0));// 7. sort
Collections.sort(v1);// 8. add new element at the end of the vector
v1.add(-1);
v1.add(1,6);// 9. delete the last element
v1.remove(v1.size()-1);}}