import
java.util.
*
;
public class ArrayTest1
... {
public static void main(String[] args)
...{
Student[] student=new Student[]...{new Student(18,"lisi"),
new Student(21,"wanghu"),
new Student(19,"zhansan"),
new Student(19,"guanghu")};
Arrays.sort(student);//对象数组必须实现Comparabel接口.否则会抛出ClassCastException
for(int i=0;i<student.length;i++)
...{
System.out.println(student[i]);
}
int index=Arrays.binarySearch(student,new Student(19,"zhansan"));//必须是排序好的数
System.out.println("index="+index);
System.out.println("student["+index+"]," + student[index]);
}
}
class Student implements Comparable
... {
int num;
String name;
public Student(int num,String name)
...{
this.num=num;
this.name=name;
}
public String toString()
...{
return "num="+num+","+"name="+name;
}
public int compareTo(Object o)
...{
Student s=(Student)o;
// return num>s.num?1:(num==s.num ? 0 : -1);
int result=num>s.num?1:(num==s.num ? 0 : -1);
if(0==result)
...{
result=name.compareTo(s.name);
//name本身是String类型的,已经实现了Comparable接口,所以可以直接用compareTo方法
}
return result;
}
}
public class ArrayTest1
... {
public static void main(String[] args)
...{
Student[] student=new Student[]...{new Student(18,"lisi"),
new Student(21,"wanghu"),
new Student(19,"zhansan"),
new Student(19,"guanghu")};
Arrays.sort(student);//对象数组必须实现Comparabel接口.否则会抛出ClassCastException
for(int i=0;i<student.length;i++)
...{
System.out.println(student[i]);
}
int index=Arrays.binarySearch(student,new Student(19,"zhansan"));//必须是排序好的数
System.out.println("index="+index);
System.out.println("student["+index+"]," + student[index]);
}
}
class Student implements Comparable
... {
int num;
String name;
public Student(int num,String name)
...{
this.num=num;
this.name=name;
}
public String toString()
...{
return "num="+num+","+"name="+name;
}
public int compareTo(Object o)
...{
Student s=(Student)o;
// return num>s.num?1:(num==s.num ? 0 : -1);
int result=num>s.num?1:(num==s.num ? 0 : -1);
if(0==result)
...{
result=name.compareTo(s.name);
//name本身是String类型的,已经实现了Comparable接口,所以可以直接用compareTo方法
}
return result;
}
}
答:1) 一组相同类型(可以是类)数据的集合;
2) 一个数组是一个对象;
3) 声明一个数组没有创建一个对象;
4) 数组能以下列形式声明:
int[] i 或 int i[]
Car[] c 或 Car c[]
2. 创建数组
答:1) 创建原始数组 int[] i = new int[2];
2) 创建类类型数组 Car[] c = new Car[100];
3) 数组创建后有初始值。
3. 初始化数组
答:1) 初始化、创建、和声明分开
int[] i;
i = new int[2];
i[0] = 0;
i[1] = 1;
2) 初始化、创建、和声明在同一时间
int[] i = {0,1};
Car[] c = {new Car(),new Car()};
4. 多维数组
答:1) 有效
int[][] i1 = new int[2][3];
int[][] i2 = new int[2][];
i2[0] = new int[2],i2[1] = new int[3];
2) 无效
int[][] i1 = new int[][3];
3) 数组长度
int[] i = new int[5];
int len = i.length;//len = 5;
Student[][] st = new Student[4][6];
len = st.length;//len = 4;
len = st[0].length;//len = 6;
请问以下哪段代码哪个可正确执行?(a,c)
1. a char[] i = {'a','b'}; i = new char[]{'b','c'};
b char[] i = {'a','b'}; i = {'b','c'};
c char[] i = new char[2]; i = new char[]{'b','c'};
d char[] i = new char[2]; i = {'b','c'};