杰瑞科技汇

ArrayUtils Java 如何高效使用?

Of course! The term "ArrayUtils" in Java most commonly refers to a utility class designed to provide helpful, static methods for working with arrays. Since Java's built-in arrays are a bit primitive (lacking methods like add(), remove(), contains(), etc.), these utility classes fill a significant gap.

ArrayUtils Java 如何高效使用?-图1
(图片来源网络,侵删)

The most famous and widely used implementation of ArrayUtils comes from the Apache Commons Lang library.


Apache Commons Lang ArrayUtils (The Standard)

This is the go-to solution for most Java developers. It's part of the Apache Commons Lang library, a set of core and reusable Java components.

Why Use It?

It saves you from writing boilerplate code for common array operations like:

  • Converting between primitive arrays and object arrays (e.g., int[] to Integer[]).
  • Converting arrays to collections (like List).
  • Checking for the presence of an element (contains).
  • Finding the index of an element (indexOf).
  • Reversing an array (reverse).
  • Adding or removing elements (by creating a new array, since arrays are fixed-size).

How to Use It

Step 1: Add the Dependency

ArrayUtils Java 如何高效使用?-图2
(图片来源网络,侵删)

You need to include the Apache Commons Lang library in your project.

Maven (pom.xml):

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.14.0</version> <!-- Use the latest version -->
</dependency>

Gradle (build.gradle):

implementation 'org.apache.commons:commons-lang3:3.14.0' // Use the latest version

Step 2: Use the Static Methods

Here are some common examples with ArrayUtils.

import org.apache.commons.lang3.ArrayUtils;
public class ArrayUtilsExample {
    public static void main(String[] args) {
        // --- Basic Operations ---
        String[] colors = {"Red", "Green", "Blue"};
        System.out.println("Original Array: " + java.util.Arrays.toString(colors));
        // 1. Check if an array contains an element
        boolean containsGreen = ArrayUtils.contains(colors, "Green");
        System.out.println("Contains 'Green'? " + containsGreen); // true
        // 2. Find the index of an element
        int index = ArrayUtils.indexOf(colors, "Blue");
        System.out.println("Index of 'Blue': " + index); // 2
        // 3. Reverse the array
        ArrayUtils.reverse(colors);
        System.out.println("Reversed Array: " + java.util.Arrays.toString(colors)); // [Blue, Green, Red]
        // --- Adding and Removing Elements ---
        // Note: These operations create a NEW array.
        // Original arrays in Java are of fixed size.
        // 4. Add an element to the end
        String[] newColors = ArrayUtils.add(colors, "Yellow");
        System.out.println("After adding 'Yellow': " + java.util.Arrays.toString(newColors)); // [Blue, Green, Red, Yellow]
        // 5. Add an element at a specific index
        newColors = ArrayUtils.add(newColors, 1, "Purple");
        System.out.println("After adding 'Purple' at index 1: " + java.util.Arrays.toString(newColors)); // [Blue, Purple, Green, Red, Yellow]
        // 6. Remove an element
        newColors = ArrayUtils.removeElement(newColors, "Green");
        System.out.println("After removing 'Green': " + java.util.Arrays.toString(newColors)); // [Blue, Purple, Red, Yellow]
        // --- Type Conversion ---
        int[] primitiveInts = {1, 2, 3, 4, 5};
        System.out.println("\nPrimitive int array: " + java.util.Arrays.toString(primitiveInts));
        // 7. Convert primitive array to an object array (Integer[])
        Integer[] objectInts = ArrayUtils.toObject(primitiveInts);
        System.out.println("Converted to Integer[]: " + java.util.Arrays.toString(objectInts));
        // 8. Convert object array to a primitive array (int[])
        int[] backToPrimitive = ArrayUtils.toPrimitive(objectInts);
        System.out.println("Converted back to int[]: " + java.util.Arrays.toString(backToPrimitive));
        // --- Converting to a List ---
        // This creates a fixed-size list backed by the original array.
        // Do NOT try to add or remove elements from this list!
        java.util.List<String> colorList = java.util.Arrays.asList(colors);
        System.out.println("\nList from array: " + colorList);
        // colorList.add("Black"); // This will throw an UnsupportedOperationException!
    }
}

Java 8+ Streams (The Modern, Built-in Alternative)

Since Java 8, you can achieve many of the same ArrayUtils functionalities using the Stream API. This is often preferred in modern Java code as it doesn't require an external library.

Here's how you can replicate the examples above using Streams.

import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
public class StreamArrayExample {
    public static void main(String[] args) {
        String[] colors = {"Red", "Green", "Blue"};
        System.out.println("Original Array: " + Arrays.toString(colors));
        // 1. Check if an array contains an element
        boolean containsGreen = Arrays.stream(colors).anyMatch("Green"::equals);
        System.out.println("Contains 'Green'? " + containsGreen); // true
        // 2. Find the index of an element
        int index = Arrays.stream(colors)
                .collect(java.util.stream.Collectors.toList())
                .indexOf("Blue");
        System.out.println("Index of 'Blue': " + index); // 2
        // 3. Reverse the array
        String[] reversedColors = Arrays.stream(colors)
                .collect(java.util.stream.Collectors.collectingAndThen(
                        java.util.stream.Collectors.toList(),
                        list -> {
                            java.util.Collections.reverse(list);
                            return list;
                        }
                )).toArray(String[]::new);
        System.out.println("Reversed Array: " + Arrays.toString(reversedColors)); // [Blue, Green, Red]
        // 4. Add an element to the end
        String[] newColors = Arrays.copyOf(colors, colors.length + 1);
        newColors[colors.length] = "Yellow";
        System.out.println("After adding 'Yellow': " + Arrays.toString(newColors)); // [Red, Green, Blue, Yellow]
        // 5. Add an element at a specific index
        newColors = Arrays.copyOf(newColors, newColors.length + 1);
        System.arraycopy(newColors, 1, newColors, 2, newColors.length - 2);
        newColors[1] = "Purple";
        System.out.println("After adding 'Purple' at index 1: " + Arrays.toString(newColors)); // [Red, Purple, Green, Blue, Yellow]
        // 6. Remove an element
        newColors = Arrays.stream(newColors)
                .filter(e -> !"Green".equals(e))
                .toArray(String[]::new);
        System.out.println("After removing 'Green': " + Arrays.toString(newColors)); // [Red, Purple, Blue, Yellow]
        // 7. Convert primitive array to an object array (Integer[])
        int[] primitiveInts = {1, 2, 3, 4, 5};
        Integer[] objectInts = Arrays.stream(primitiveInts).boxed().toArray(Integer[]::new);
        System.out.println("\nConverted to Integer[]: " + Arrays.toString(objectInts));
        // 8. Convert object array to a primitive array (int[])
        int[] backToPrimitive = Arrays.stream(objectInts).mapToInt(Integer::intValue).toArray();
        System.out.println("Converted back to int[]: " + Arrays.toString(backToPrimitive));
    }
}

Guava's Arrays (Another Powerful Alternative)

Google's Guava library also provides excellent utilities for arrays in its com.google.common.primitives package. It's very similar in spirit to Apache Commons Lang.

Maven Dependency:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>33.0.0-jre</version> <!-- Use the latest version -->
</dependency>

Example Usage:

import com.google.common.primitives.Ints;
import com.google.common.primitives.Strings;
public class GuavaExample {
    public static void main(String[] args) {
        // Contains
        int[] numbers = {1, 2, 3, 4};
        boolean containsThree = Ints.contains(numbers, 3);
        System.out.println("Contains 3? " + containsThree);
        // IndexOf
        int index = Ints.indexOf(numbers, 4);
        System.out.println("Index of 4: " + index);
        // Convert to a List (creates a new, mutable list)
        java.util.List<Integer> numberList = Ints.asList(numbers);
        System.out.println("List from array: " + numberList);
        numberList.add(5); // This works!
        System.out.println("After adding 5: " + numberList);
        // Concatenate arrays
        int[] moreNumbers = {5, 6, 7};
        int[] allNumbers = Ints.concat(numbers, moreNumbers);
        System.out.println("Concatenated array: " + Arrays.toString(allNumbers));
    }
}

Comparison and Summary

Feature Apache Commons Lang ArrayUtils Java 8+ Streams Guava Primitives
Dependency Required (commons-lang3) None (Built-in) Required (guava)
Ease of Use Very simple, method names are intuitive. Can be verbose for some operations (like reversing). Very simple and powerful.
Performance Generally very good, optimized C-style loops. Can have a slight overhead due to stream creation, but JIT often optimizes this. Generally very good.
Key Strength Extremely comprehensive, covers almost all needs. No external dependency, integrates well with modern Java functional style. Excellent for converting between primitives/collections and fast operations.
Best For General purpose, quick solutions, projects already using Commons. Modern Java projects, functional programming style, avoiding external dependencies. Projects already using Guava, or when you need fast conversions from primitives.

Recommendation

  • For most projects: Use Apache Commons Lang ArrayUtils. It's the standard, well-documented, and covers a vast range of use cases with simple, readable code.
  • For modern, dependency-free projects: Use the Java 8+ Stream API. It's powerful and integrates seamlessly with the rest of the Java language.
  • If you're already using Guava: Its Primitives classes are a fantastic and efficient choice.
分享:
扫描分享到社交APP
上一篇
下一篇