杰瑞科技汇

Java数组与字符串如何高效转换?

Of course! Let's dive deep into Java arrays of strings. This is a fundamental concept in Java, and understanding it is crucial for any developer.

Java数组与字符串如何高效转换?-图1
(图片来源网络,侵删)

We'll cover:

  1. Declaring and Initializing a String array.
  2. Accessing and Modifying elements.
  3. Getting the Length of the array.
  4. Iterating through the array.
  5. Common Operations (sorting, searching, converting).
  6. Important Characteristics (immutability, fixed size).

Declaring and Initializing a String Array

There are several ways to declare and initialize a String array in Java.

a) Declaration Only

This creates a reference to an array, but the array itself is not yet created. It's null.

String[] fruits; // Preferred style
String fruits2[]; // Also works, but less common

b) Initialization with new

This creates a new array with a specified size. The elements are initialized to null by default.

Java数组与字符串如何高效转换?-图2
(图片来源网络,侵删)
// Create an array that can hold 3 strings
String[] colors = new String[3];
// At this point, colors[0], colors[1], and colors[2] are all null

c) Initialization with Values

This is the most common way. You create the array and provide its initial values simultaneously.

// Create and populate the array in one line
String[] planets = { "Mercury", "Venus", "Earth", "Mars" };
// You can also split the declaration and initialization
String[] weekdays;
weekdays = new String[] { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" };

d) Initialization from a String

You can easily create an array from a single string by splitting it on a delimiter.

String csvData = "apple,banana,cherry,date";
String[] fruitsArray = csvData.split(","); // Splits the string by the comma
// fruitsArray is now: ["apple", "banana", "cherry", "date"]

Accessing and Modifying Elements

You access elements using their index, which starts at 0.

String[] languages = { "Java", "Python", "C++" };
// Accessing an element
String firstLanguage = languages[0]; // firstLanguage is "Java"
String secondLanguage = languages[1]; // secondLanguage is "Python"
// Modifying an element
languages[2] = "C#"; // The array is now: ["Java", "Python", "C#"]
// Accessing an index that doesn't exist throws an ArrayIndexOutOfBoundsException
// String lang = languages[5]; // This will crash your program

Getting the Length of the Array

Use the .length property (not a method like .length() for strings) to find the number of elements in the array.

Java数组与字符串如何高效转换?-图3
(图片来源网络,侵删)
String[] cars = { "Toyota", "Honda", "Ford", "BMW" };
int numberOfCars = cars.length; // numberOfCars is 4

Iterating Through the Array

There are two primary ways to loop through an array.

a) Classic for Loop

This gives you access to the index, which can be useful if you need it.

String[] technologies = { "AI", "Blockchain", "Cloud", "IoT" };
for (int i = 0; i < technologies.length; i++) {
    System.out.println("Technology at index " + i + ": " + technologies[i]);
}

b) Enhanced for-each Loop

This is more modern and concise. It's perfect when you just need the value of each element and don't care about the index.

String[] frameworks = { "Spring", "Hibernate", "JUnit" };
for (String framework : frameworks) {
    System.out.println("Framework: " + framework);
}

Common Operations

a) Sorting

To sort an array of strings alphabetically, use the Arrays.sort() utility from the java.util.Arrays class.

import java.util.Arrays;
String[] names = { "Charlie", "Alice", "David", "Bob" };
Arrays.sort(names); // Sorts the array in-place
// names is now: ["Alice", "Bob", "Charlie", "David"]
System.out.println(Arrays.toString(names)); // A handy way to print the array

b) Searching

You can search for an element using Arrays.binarySearch(). Important: The array must be sorted first for this to work correctly.

import java.util.Arrays;
String[] sortedFruits = { "Apple", "Banana", "Cherry" };
int index = Arrays.binarySearch(sortedFruits, "Banana"); // Returns 1
int indexNotFound = Arrays.binarySearch(sortedFruits, "Grape"); // Returns -4 (insertion point)
if (index >= 0) {
    System.out.println("Found Banana at index: " + index);
} else {
    System.out.println("Grape not found. Insertion point: " + indexNotFound);
}

c) Converting to a List

You can convert an array to a List using Arrays.asList().

import java.util.Arrays;
import java.util.List;
String[] techStack = { "React", "Node.js", "PostgreSQL" };
List<String> techList = Arrays.asList(techStack);
// Note: This creates a fixed-size list. You cannot add or remove elements from it.
// techList.add("Docker"); // This will throw an UnsupportedOperationException

d) Copying an Array

Use Arrays.copyOf() to create a new array with a copy of the elements.

import java.util.Arrays;
String[] original = { "one", "two", "three" };
String[] copy = Arrays.copyOf(original, original.length);
// Now, original and copy are two separate arrays in memory.
copy[0] = "ONE";
System.out.println("Original: " + Arrays.toString(original)); // [one, two, three]
System.out.println("Copy:     " + Arrays.toString(copy));     // [ONE, two, three]

Important Characteristics

a) Immutability of String Elements

Remember that String objects are immutable. When you "modify" a string in an array, you are not changing the original string object; you are replacing the reference in the array with a new string object.

String[] words = { "Hello" };
words[0] = words[0] + " World"; // "Hello World" is a new string object
// The original "Hello" string might still be in memory if no other references point to it.

b) Fixed Size

The size of a Java array is fixed when it's created. You cannot add or remove elements from it. If you need a dynamic collection that can grow or shrink, you should use an ArrayList instead.

// This is a fixed-size array
String[] fixedArray = new String[5];
fixedArray[0] = "A";
// fixedArray[5] = "F"; // Throws ArrayIndexOutOfBoundsException
// This is a dynamic list (better for most use cases)
import java.util.ArrayList;
ArrayList<String> dynamicList = new ArrayList<>();
dynamicList.add("A");
dynamicList.add("B");
dynamicList.add("C");
// The list can grow dynamically
dynamicList.add("D");
dynamicList.add("E");
dynamicList.add("F"); // No problem!

Summary Table

Task Code Example
Declare String[] myArray;
Initialize String[] myArray = {"A", "B"};
Access Element String val = myArray[0];
Modify Element myArray[0] = "New Value";
Get Length int len = myArray.length;
Sort Arrays.sort(myArray);
Search (sorted) int index = Arrays.binarySearch(myArray, "target");
Print Array System.out.println(Arrays.toString(myArray));
分享:
扫描分享到社交APP
上一篇
下一篇