Arrays类

                      Arrays类

一个全部由静态方法构成的类,提供了许多有用的操作数组的方法。

1. asList:将指定的数组转换为List;
2. binarySearch:采用二分搜索方法从数组中查找指定的值
3. deepEquals:比较两个数组是否“深层次相等”,5.0引入
4. deepHashCode:计算数组的“深层次哈希码”,5.0引入
5. deepToString:将数组转换为字符串,5.0引入
6. equals:比较两个数组是否相等
7. fill:用指定值填充数组
8. hashCode:计算数组的哈希值,5.0引入
9. sort:对数组进行升序排序
10. toString:将数组转换为字符串,5.0引入。

代码
import java.util.*;
class ArraysTest
{
public static void main(String[] args)
{
char list[] = {'a','c','u','b','e','p','f','z'};
Arrays.sort(list);
// 升序排列
for (int i = list.length - 1; i >= 0; i-- ) {// 降序排列
System.out.print(list[i] + ", ");// z, u, p, f, e, c, b, a,
}
System.out.println();
int index = Arrays.binarySearch(list, 'p');
System.out.println(index);
// 5
}
}

 

注意:必须经过排序之后才能使用二分法进行查找。

 


数组的复制:System.arraycopy()。
public static void arraycopy(Object src,
int srcPos,
Object  dest,
int destPos,
int length)
The srcPos argument is negative.
The destPos argument is negative.
The length argument is negative.
srcPos+length is greater than src.length, the length of the source array.
destPos+length is greater than dest.length, the length of the destination array 

public class ArrayCopy {
public static void main(String[] args) {
int[] num1 = new int[]{1,2,3,4};
int[] num2 = new int[5];
System.arraycopy(num1,
0,num2,0,num1.length);
for(int i = 0;i<num2.length;i++) {
System.out.print(num2[i]
+"");
}
num2[
1] = 8;// 数组和对象都是引用类型。
System.out.println(num1[1]);// 为什么打印不是8呢?

Point[] pt1
= new Point[]{new Point(1,1),new Point(2,2),new Point(3,3)};
Point[] pt2
= new Point[3];
System.arraycopy(pt1,
0,pt2,0,pt1.length);
for(int i = 0;i < pt2.length;i++) {
System.out.println(
"x = "+ pt2[i].x + " y = "+ pt2[i].y);
}
pt2[
2].x = 9;
pt2[
2].y = 9;
System.out.println(
"x = "+pt1[2].x+" y = " + pt1[2].y);
}
}

class Point {
int x,y;
public Point(int x,int y) {
this.x = x;
this.y = y;
}
}

 

 

posted @ 2010-12-22 13:06  meng72ndsc  阅读(257)  评论(0编辑  收藏  举报