如何将单个字符串复制为包含其多份副本的字符串数组?
Absolutely! This is totally doable in Java, and there are several simple, clean ways to get the exact result you're after—an array containing two identical copies of your "Hello" string. Let me walk you through each approach:
1. Direct Array Initialization (Simplest for Fixed Length)
If you know you only need two copies, this is the quickest and most straightforward method. Just initialize the array with your original string twice:
String original = "Hello"; String[] duplicatedArray = {original, original};
Since Java Strings are immutable, both elements in the array point to the same String instance. That means their values will always stay identical—no risk of one changing and breaking the other. Super efficient and perfect for your use case.
2. Using Arrays.fill() (Ideal for Dynamic Lengths)
If you might need to adjust the number of copies later (say, 3 or 10 instead of 2), Arrays.fill() is a handy utility from the java.util package:
import java.util.Arrays; public class StringDuplicateArray { public static void main(String[] args) { String original = "Hello"; int numCopies = 2; // Easy to tweak this number later String[] duplicatedArray = new String[numCopies]; Arrays.fill(duplicatedArray, original); } }
This method fills every slot in the array with the original string reference, ensuring consistent values across all elements. Great for writing reusable, flexible code.
3. Manual Loop (For Full Control)
While this is overkill for a 2-element array, a loop gives you full control if you ever need to add custom logic (like modifying each copy before adding it, though that's not needed here):
String original = "Hello"; String[] duplicatedArray = new String[2]; for (int i = 0; i < duplicatedArray.length; i++) { duplicatedArray[i] = original; }
It's a bit more verbose, but it's easy to understand and adapt if your requirements change down the line.
Quick Side Note on String Immutability
Just to clarify: since Java Strings are immutable, you don't have to worry about one copy altering the other. All references in the array point to the same unchangeable String object, so their values will always match. If for some edge case you needed separate String instances with the same value (you don't here), you could use new String(original)—but that's unnecessary and less efficient, so stick with the original reference.
内容的提问来源于stack exchange,提问作者Steven Ng

