详见代码:
public class Main { public static void main(String[] args) { //匿名数组的定义方式new int[]{1,5,1,9} int a[] = {1,5,1,9}; int b[]; b = a; System.out.println(b[1]); b = new int[]{1,5,1,9};//这是上面三行代码的简化 System.out.println(b[1]); } }
import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.sql.Date; import java.util.Arrays; public class Main { public static void main(String[] args) { int ary[] = {1,2,3,4,5,6,7,8,9,10}; //System.out.println(ary.length); int b[] = Arrays.copyOf(ary,ary.length);//把ary里的元素拷贝到b System.out.println(b[1]); System.out.println(b.length);//b的元素个数和ary数组相同 ary = Arrays.copyOf(ary, 2*ary.length);//把ary数组的大小变大2倍 System.out.println(ary.length); } }
代码:
import java.util.Arrays; public class Main { public static void main(String[] args) { int ary[] = {8,4,56,6,7,21,1}; Arrays.sort(ary); //for(int i = 0;i< ary.length;i++) for(int i : ary) { //System.out.println("ary["+i+"] = "+ary[i]); System.out.println("ary["+i+"] = "+i); } } }
for(int i = 0;i<ary.length;i++) { System.out.println(ary[i]);} ↓ for(int i : ary) System.out.println(i);//两者等价
应用Math类中的random方法
(int)(Math.random()*n)方法随机产生一个0到1之间(包含0,不包含1)的随机浮点数,用n乘以这个浮点数就可以得到0到n-1之间的随机数
import java.util.Arrays; public class Main { public static void main(String[] args) { int ary[] = {8,4,56,6,7,21,1}; Arrays.sort(ary); int ran = (int)(Math.random()*ary.length); System.out.println("生成的随机数是"+ran); System.out.println("打印的数组元素"+ary[ran]); } }
原文:http://blog.csdn.net/wjw0130/article/details/39483109