0%

6.29数组

2017年6月29日 下午12:09

第一个部分:数组定义

定义的方法:
1. int num[]= new int[10];必须说明长度 int初始化为0
2. int []num;
num=new int[5]
3. int num[]=new int[]{1,2,3,4}
4. int num[]={1,2,4,5,6,7}
String string1[] = {“1”,”2”};

长度方面的错:
1. String str[] = new String[];不能不说明长度
2. int num[10];编译出错 说明长度情况下,必须要有指向的内容
3. String str[] = new String[3]{“1”,”2”,”3”}; 编译错

先定义后初始化(一对三错):
String str[];
str = new String[]{“1”,”2”};对

String str[];
str[] = new String[]{"1","2"};错

String str[];
str = {"1","2"};错

int str[];
str ={1,2};错

总结:分开只能按1写

第二部分:局部 and 全局 基本类型 and 对象类型 数组 and 非数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package package1;

public class Test5 {
static Student student[] = new Student[10];
static String string[] = new String[10];
static Student student2[] = new Student[]{new Student(),new Student()};
static String string2[] = new String[]{new String(),new String()};
public static void main(String[] args) {

System.out.println(student.length);//new Student[10] 定义长度
System.out.println(student[0]);//但是没在堆中定义空间

System.out.println(string.length);
System.out.println(string[0]);//但是没在堆中定义空间

System.out.println(student2.length);
System.out.println(student2[0]);

System.out.println(string2.length);
System.out.println(string2[0]);//这里输出的是""打印出来为空
}

}

输出:

1
2
3
4
5
6
7
10
null
10
null
2
package1.Student@677327b6
2

[“”]自己加的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package package1;

public class Test4 {

public static void main(String[] args) {

Student student[] = new Student[10];
System.out.println(student.length);//new Student[10] 定义长度
System.out.println(student[0]);//但是没在堆中定义空间

String string[] = new String[10];
System.out.println(string.length);
System.out.println(string[0]);//但是没在堆中定义空间

Student student2[] = new Student[]{new Student(),new Student()};
System.out.println(student2.length);
System.out.println(student2[0]);

String string2[] = new String[]{new String(),new String()};
System.out.println(string2.length);
System.out.println(string2[0]);//这里输出的是""打印出来为空

//Student String 数组是完全一样的
//除了new的默认值以外,String的默认值是"" Student默认值为包名+地址

}

}

输出:

1
2
3
4
5
6
7
8
10
null
10
null
2
package1.Student@677327b6
2
[“”]自己加的

发现:
1. 他们的输出是一样的,说明局部变量的概念对数组无效


图1:对象声明为局部

图2:对象声明为全局
发现:
1. 对于非数组对象(单个对象),局部变量概念有效

加入基本类型后:
1. 局部中:
基本类型 对象类型
数组(只定义长度) 0 null
非数组(只对象声明) 错 错
3. 全局中:
基本类型 对象类型
数组(只定义长度) 0 null
非数组(只对象声明) 0 null

总结:
对于数组类型: 基本类型是0,对象类型为null
对于非数组:局部中一定错 ,全局中 0 和 null

String 和 Student的区别(单个对象+以初始化)

1. String的默认值是"" ,Student默认值为包名+地址
2. 其他的,Student String 数组是完全一样的 

注:注意前提为以初始化