Java中更高效的对象初始化方式?批量初始化20个对象求简化方案
Hey there! Let's tackle this problem—first, I notice a small typo in your code: you declared a Gallina[] gallina array but are assigning to gato variables. I'll assume you meant to work with a Gato[] array that needs a total of 30 objects (10 existing + 20 more). Here are some simpler ways to handle this:
If many of your Gato properties are repetitive (like the name "Fluffy" in your example), you can store variable parameters (gender, breed, age) in arrays/lists and loop through them to create objects:
// Correct array declaration with total capacity 30 Gato[] gato = new Gato[30]; // Keep your existing 10 initialized objects gato[0] = new Gato(true, "Siames", "Fluffy", 10); gato[1] = new Gato(false, "Persa", "Fluffy", 11); gato[2] = new Gato(true, "Maine Coon", "Fluffy", 9); // ... add the remaining 7 existing objects ... // Define reusable parameters for the 20 new cats boolean[] genders = {true, false, true, false}; String[] breeds = {"British Shorthair", "Scottish Fold", "Chartreux", "Cornish Rex"}; int[] ages = {2, 5, 7, 3}; // Batch-create the 20 additional objects for (int i = 10; i < 30; i++) { int paramIndex = i % 4; // Cycle through parameter arrays gato[i] = new Gato(genders[paramIndex], breeds[paramIndex], "Fluffy", ages[paramIndex]); }
Encapsulate the Gato instantiation logic in a static factory method. This makes your code cleaner, easier to maintain, and reduces repetition:
// Create a simple factory class (or add this method directly to your Gato class) public class GatoFactory { // Basic factory method with all parameters public static Gato createGato(boolean isMale, String breed, String name, int age) { return new Gato(isMale, breed, name, age); } // Overloaded method for common defaults (e.g., fixed name "Fluffy") public static Gato createGato(boolean isMale, String breed, int age) { return new Gato(isMale, breed, "Fluffy", age); } } // Usage in your main code Gato[] gato = new Gato[30]; // Initialize existing 10 objects with the factory gato[0] = GatoFactory.createGato(true, "Siames", 10); gato[1] = GatoFactory.createGato(false, "Persa", 11); // ... add the rest of your existing objects ... // Batch-add 20 new cats for (int i = 10; i < 30; i++) { boolean isMale = i % 2 == 0; String[] breeds = {"British Shorthair", "Scottish Fold", "Chartreux", "Cornish Rex"}; String breed = breeds[i % breeds.length]; int age = (int)(Math.random() * 15) + 1; // Random age 1-15 gato[i] = GatoFactory.createGato(isMale, breed, age); }
If you don't need a fixed-size array, ArrayList<Gato> is more flexible—you can add objects on the fly without predefining total capacity:
import java.util.ArrayList; import java.util.List; List<Gato> gatos = new ArrayList<>(); // Add your existing 10 cats gatos.add(new Gato(true, "Siames", "Fluffy", 10)); gatos.add(new Gato(false, "Persa", "Fluffy", 11)); // ... add the remaining 8 existing objects ... // Batch-add 20 new cats for (int i = 0; i < 20; i++) { boolean isMale = Math.random() > 0.5; String[] breeds = {"British Shorthair", "Scottish Fold", "Chartreux", "Cornish Rex"}; String breed = breeds[i % breeds.length]; int age = (int)(Math.random() * 12) + 2; // Random age 2-13 gatos.add(new Gato(isMale, breed, "Fluffy", age)); } // Convert to array later if needed Gato[] gatoArray = gatos.toArray(new Gato[0]);
For a more concise, functional approach, use Streams to generate the 20 new objects:
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; // Start with your existing 10 cats List<Gato> existingGatos = Arrays.asList( new Gato(true, "Siames", "Fluffy", 10), new Gato(false, "Persa", "Fluffy", 11), // ... add the remaining 8 existing objects ... ); // Generate 20 new cats with Stream List<Gato> newGatos = IntStream.range(0, 20) .mapToObj(i -> { boolean isMale = i % 2 == 0; String[] breeds = {"British Shorthair", "Scottish Fold", "Chartreux", "Cornish Rex"}; String breed = breeds[i % breeds.length]; int age = i + 1; // Sequential age example return new Gato(isMale, breed, "Fluffy", age); }) .collect(Collectors.toList()); // Merge existing and new cats existingGatos.addAll(newGatos); // Convert to array if needed Gato[] gatoArray = existingGatos.toArray(new Gato[0]);
内容的提问来源于stack exchange,提问作者user9338258

