//静态初始化 int[] numbers = new int[] { 3, 5, 12, 8, 7}; String[] names = { "Miracle","Miracle He" };//使用静态初始化的简化形式 //动态初始化 int[] numbers = new int[5]; String[] names = new String[2]; |
public class TestArray { public static void main(String[] args) { String[] names = new String[3]; names[0] = "Miracle"; names[1] = "Miracle He"; //以下代码将输出Miracle Miracle He null //还可以使用foreach来遍历 for(String name : names) { System.out.print(name + " "); } } } |
public class TestForEach { public static void main(String[] args) { int[] numbers = { 3, 5, 12, 8, 7 }; for(int number : numbers) { int num = number * 10; System.out.print(num + ","); } System.out.println(""); //numbers仍然未发生变化(如果换成for将改变) for(int i = 0;i < numbers.length;i++) { System.out.print(numbers + ","); } } } |
public class TestArrayLength { public static void main(String[] args) { int[] numbers = { 3, 5, 12 }; int[] digits = new int[4]; System.out.println("digits数组长度:" +digits.length);//4 for(int number : numbers) { System.out.print(number + ",");//3,5,12, } System.out.println(""); for(int digit : digits) { System.out.print(digit +",");//0,0,0,0, } System.out.println(""); digits = numbers; System.out.println("digits数组长度:" +digits.length);//3 } } |
public class TestPrimitiveArray { public static void main(String[] args) { //1.定义数组 int[] numbers; //2.分配内存空间 numbers = new int[4]; //3.为数组元素指定值 for(int i = 0;i < numbers.length;i++) { numbers = i * 10; } } } |
class Person { public int age; public String name; public void display() { System.out.println(name + "的年龄是: " + age); } } public class TestReferenceArray { public static void main(String[] args) { //1.定义数组 Person[] persons; //2.分配内存空间 persons = new Person[2]; //3.为数组元素指定值 Person p1 = new Person(); p1.age = 28; p1.name = "Miracle"; Person p2 = new Person(); p2.age = 30; p2.name = "Miracle He"; persons[0] = p1; persons[1] = p2; //输出元素的值 for(Person p : persons) { p.display(); } } } |
1.jpg (17.32 KB, 下载次数: 17)
图一
2.jpg (20.5 KB, 下载次数: 22)
3.jpg (20.79 KB, 下载次数: 14)
图三
4.jpg (36.49 KB, 下载次数: 14)
图四
5.jpg (44.02 KB, 下载次数: 17)
6.jpg (29.36 KB, 下载次数: 15)
图六
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |