js css html

Java--java.util.Arrays类-2

2022-09-24  本文已影响0人  李赫尔南

【示例】数组元素是引用类型的排序(Comparable接口的应用)
import java.util.Arrays;
public class Test {
  public static void main(String[] args) {
    Man[] msMans = { new Man(3, "a"), new Man(60, "b"), new Man(2,"c") };
    Arrays.sort(msMans) ;
    System.out.println(Arrays.toString(msMans));
  }
}
class Man implements Comparable {
  int age;
  int id;
  String name;

  public Man(int age, String name) {
    super();
    this.age = age;
    this.name = name;

  public String tostring() {
    return this.name;
  }

  public int compareTo(Object o) {
    Man man = (Man) o;
    if (this.age < man.age) {
      return -1;
    }
    if (this.age > man.age) {
      return 1;
    }
    return 0;
  }
}

【示例】二分法查找

import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        int[] a = {11,2,23,223,3,121,9};
        System.out.println(Arrays.toString(a));
        Arrays.sort(a); //使用二分法查找,必须先对数组进行排序;
        System.out.println(Arrays.toString(a));  
        //返回排序后新的索引位置,若未找到返回负数。
        System.out.println("该元素的索引:"+ Arrays.binarySearch(a, 12));
    }
}

输出:
  [11,2,23,223,3,121,9]
  [2,3,9,11,23,121,223]
  该元素的索引:2

上一篇下一篇

猜你喜欢

热点阅读