完整教程:Java基础之数组(附带Comparator)

基础概念

int[] anArray = new int[10];

只有创建对象时才会使用new关键字,所以数组是个对象。

数组中的每个元素都会被初始化为默认值,int 类型的就为 0,Object 类型的就为 null。 不同数据类型的默认值不同

可变参数组

1. 基本概念

  • 定义:允许函数接受不确定数量的同类型参数,这些参数会被自动封装为一个数组。
  • 作用:简化方法调用,避免为不同参数数量重载多个方法。

2. 语法示例

public
void printNumbers(
int... numbers) {
for (
int num : numbers) {
System.out.println(num)
;
}
}
// 调用方式
printNumbers(1
, 2
, 3
)
;
// 输出: 1 2 3
printNumbers(10
, 20
)
;
// 输出: 10 20
printNumbers(
)
;
// 可以不传参数

数组与List

将数组转为List,使用Arrays类

//1
List aList = Arrays.asList(1, 2, 3, 4, 5);
//2
int[] anArray = new int[] {1, 2, 3, 4, 5};
List aList = Arrays.stream(anArray).boxed().collect(Collectors.toList());
  • .boxed()转换为对应的包装类对象。
  • **.collect(Collectors.toList())**此操作会把流中的元素收集到一个List集合中。

还有一个需要注意的是,Arrays.asList 方法返回的 ArrayList 并不是 java.util.ArrayList,它其实是 Arrays 类的一个内部类:

private static class ArrayList extends AbstractList
implements RandomAccess, java.io.Serializable{}

如果需要添加元素或者删除元素的话,需要把它转成 java.util.ArrayList

new ArrayList<>(Arrays.asList(anArray));

Comparator类

1,基本概念

int compare(T o1, T o2)
返回值含义
负整数o1 应该排在 o2 前面 (o1 < o2)
o1 和 o2 相等 (o1 == o2)
正整数o1 应该排在 o2 后面 (o1 > o2)

因此

  • o1 - o2 → 升序排序
  • o2 - o1 → 降序排序
Comparator lengthComparator = new Comparator() {
  @Override
  public int compare(String s1, String s2) {
    return s1.length() - s2.length();
  }
};
//使用Lamda
Comparator lengthComparator = (s1, s2) -> s1.length() - s2.length();

2,使用Comparator的静态方法(Java 8+)

// 按字符串长度排序
Comparator lengthComparator = Comparator.comparingInt(String::length);
// 按字符串长度降序排序
Comparator descLengthComparator = Comparator.comparingInt(String::length).reversed();

3,常用Comparator方法

1. comparing() 和 comparingInt()/comparingLong()/comparingDouble()

// 按Person的age属性排序
Comparator byAge = Comparator.comparing(Person::getAge);
// 按字符串长度排序
Comparator byLength = Comparator.comparingInt(String::length);
特性comparing()comparingInt()/comparingLong()/comparingDouble()
适用类型任何Comparable类型仅限基本数据类型(int/long/double)
性能可能有装箱开销无装箱开销,性能更好
方法参数FunctionToIntFunction/ToLongFunction/ToDoubleFunction
null处理需要额外处理需要额外处理
链式调用支持thenComparing()支持thenComparingInt()等对应方法

2. thenComparing() - 多级排序

// 先按age排序,age相同再按name排序
Comparator byAgeThenName = Comparator
.comparingInt(Person::getAge)
.thenComparing(Person::getName);

3. naturalOrder() 和 reverseOrder()

// 自然顺序排序
Comparator natural = Comparator.naturalOrder();
// 逆序排序
Comparator reverse = Comparator.reverseOrder();

4. nullsFirst() 和 nullsLast() - 处理null值

// null值排在前面
Comparator nullsFirst = Comparator.nullsFirst(Comparator.naturalOrder());
// null值排在后面
Comparator nullsLast = Comparator.nullsLast(Comparator.naturalOrder());

4,例子

----------------基本排序--------------
List words = Arrays.asList("apple", "banana", "pear", "orange");
// 按长度排序
words.sort(Comparator.comparingInt(String::length));
System.out.println(words); // [pear, apple, banana, orange]
// 按长度降序
words.sort(Comparator.comparingInt(String::length).reversed());
System.out.println(words); // [banana, orange, apple, pear]
--------------对象排序-----------------
class Person {
  String name;
  int age;
  // 构造方法、getter、setter省略
}
List people = Arrays.asList(
  new Person("Alice", 25),
  new Person("Bob", 30),
  new Person("Charlie", 20)
);
// 按年龄排序
people.sort(Comparator.comparingInt(Person::getAge));
System.out.println(people); // [Charlie(20), Alice(25), Bob(30)]
// 按年龄降序,然后按姓名升序
people.sort(Comparator
.comparingInt(Person::getAge).reversed()
.thenComparing(Person::getName));
System.out.println(people); // [Bob(30), Alice(25), Charlie(20)]
-----------处理null值-------------
List wordsWithNull = Arrays.asList("apple", null, "banana", null, "pear");
// null值排在前面
wordsWithNull.sort(Comparator.nullsFirst(Comparator.naturalOrder()));
System.out.println(wordsWithNull); // [null, null, apple, banana, pear]
// null值排在后面
wordsWithNull.sort(Comparator.nullsLast(Comparator.reverseOrder()));
System.out.println(wordsWithNull); // [pear, banana, apple, null, null]

排序与查找

  • Arrays.sort()方法。

  • 自定义排序(使用Comparator)

//本数据类型按照升序排列
int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray);
//自定义排序
//只对 1-3 位置上的元素进行反序,[A, Z, E, B, C]
String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3,
Comparator.comparing(String::toString).reversed());
  • 二分查找,Arrays.binarySearch()
//保证数组已排序
int[] anArray = new int[] {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(anArray, 4);

数组复制

// 复制整个数组(长度相同)
static int[] copyOf(int[] original, int newLength)
// 复制数组的指定范围
static int[] copyOfRange(int[] original, int from, int to)
------------例子-------------
int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, 3);  // [1, 2, 3]
int[] rangeCopy = Arrays.copyOfRange(original, 1, 4);  // [2, 3, 4]

其他

数组去重

int[] numbers = {1, 2, 2, 3, 4, 4, 4, 5};
Arrays.sort(numbers);
int[] unique = Arrays.stream(numbers).distinct().toArray();
// 结果: [1, 2, 3, 4, 5]

数组填充

// 用指定值填充整个数组
static void fill(int[] a, int val)
// 填充数组的指定范围 [fromIndex, toIndex)
static void fill(int[] a, int fromIndex, int toIndex, int val)
--------------例子-----------
int[] numbers = new int[5];
Arrays.fill(numbers, 1);  // [1, 1, 1, 1, 1]
// 部分填充
Arrays.fill(numbers, 1, 3, 9);  // [1, 9, 9, 1, 1]
posted @ 2025-07-20 16:15  yfceshi  阅读(6)  评论(0)    收藏  举报