分类: Java
2015-03-11 14:17:23
java中所有的数组都有一个缺省的属性length,用于获取数组元素的个数
数组的复制:System.arraycopy(); 数组的排序Arrays.sort(); 在已排序的数组中查找某个元素Arrays.binarySearch()
arraycopy(
Object src, //源数组
int srcPos, //拷贝位置
Object dest, //目的数组
int desPos, //目的位置
int length //长度
)
class ArrayTest
{
public static void main(String[] args)
{
int[] num1 = new int[]{4,2,3};
int[] num2 = new int[3];
System.arraycopy(num1, 0, num2, 0, num1.length); //复制数组
Arrays.sort(num1); //排序,升序,需要引入java.util包
int index = Arrays.binarySearch(num1,2); //搜索的对应元素的序号
for(int i=0; i
Point[] p1 = new Point[]{new Point(1,1), new Point(2,2), new Point(3,3) };
Point[] p2 = new Point[3];
System.arraycopy(p1, 0, p2, 0, p1.length); //复制类数组
p2[1].x = 100;
p2[1].y = 100;
System.out.println(p1[1].x + p1[1].y) //p1也被修改了,因为类复制的时候,拷贝的是引用,也就是说拷贝的是地址
Student ss = new Studen[]{new Student(1, "zs'), new Student(2, "ls"), new Student(3, "ww")};
Arrays.sort(ss);
int index = Arrays.binarySearch(ss new Student(2, "lisi")); //搜索必须在排序之后进行
}
}
class Point
{
int x,y;
Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
class Student implements Comparable //类排序,需要实现Comparable方法
{
int age;
String name ;
Student(int age, String name)
{
this.age = age;
this.name = name;
}
public String toString()
{
return "age = " + age + "name = " +name;
}
public int compareTo(Object o) // 自己实现排序,实现compareTo方法
{
Student s = (Student)o;
// return age > s.age ? 1 : (age == s.age ? 0 : -1); //按照年龄实现排序
result = age > s.age ? 1: (age == s.age ? 0 : -1);
if(result == 0)
{
result = name.compareTo(s.name);
}
return result;
}
}