Arrays类中equals,sort,toString方法讲解

Arrays类

用于数组工具类,里面定义了常见的操作数组的静态方法

equals方法

声明:public static boolean equals(type[]a, type[]b)

用于比较两个数组是否相同, 它们必须有相同数量的元素,而且数组的每个元素必须与另一个数组的相对应位置上的元素相等

sort方法

作用于数组的所有元素

1.public static void sort(type[] a)

public class Main {
public static void main(String[] args) {
int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a);
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
}

得到的数据固定按照升序排列 0 1 2 3 4 5 6 7 8 9

2.public static void sort(type []a,int fromindex(包括), int toindex (不包括))

public class Main {
public static void main(String[] args) {
int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
Arrays.sort(a, 0, 3);//升序排列
for(int i = 0; i < a.length; i ++) {
System.out.print(a[i] + " ");
}
}
}

得到结果 7 8 9 2 3 4 1 0 6 5

3、public static void sort(T[] a,int fromIndex,int toIndex, Comparator c)

通过添加拘束,把默认的升序排列改为降序排列

public class Main {
     public static void main(String[] args) {
         //注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
         //而要使用它们对应的类
         Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
         //定义一个自定义类MyComparator的对象
         Comparator cmp = new MyComparator();
         Arrays.sort(a, cmp);
         for(int i = 0; i < a.length; i ++) {
             System.out.print(a[i] + " ");
         }
    }
 }

运行结果为 9 8 7 6 5 4 3 2 1 0

toString方法

public static String toString(type[]a)

返回指定数组的字符串表示形式

用来将数组转换成String类型输出的

public class test2 {   
public static void main(String[] args) {  
int[]num={12,33,45,66,77};     
System.out.println(Arrays.toString(num));    }
}

运行得到12 33 45 66 77

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值