如何在Java中动态创建变量?

我需要创建新的变量Strings

 String person1 = "female"; String person2 = "female"; ........ ........ String person60 = "male"; ........ String person100 = "male"; 

这就是我试过的

 for (int i = 1; i <101; i++) { if (i<60) { String person+i = "female"; } else { String person+i = "male"; } } 

任何人都可以帮我纠正这段代码吗?

Map允许您将任何键与任何值相关联。 在这种情况下,键是变量的名称,值是值

 Map details = new HashMap<>(); for (int i = 1; i <101; i++) { if (i<60) { details.put("person" + i, "female"); } else { details.put("person" + i, "male"); } } 

你很亲密 如果您将每个人的性别存储在一个数组中,您可以这样做:

 String[] persons = new String[100] for (int i = 0; i < persons.length; i++) { if (i<60) { persons[i] = "female"; } else { persons[i] = "male"; } } 

或者,如果一个人不仅仅是一个性别,考虑创建一个持有性别字段的Person ,然后拥有一个Person数组。 您可以以类似的方式设置性别。

您可以使用Map ,其中键是您的“变量名称”,值是该变量的值。

您将需要一个可以动态确定的某种大小的String[]
然后,为数组元素赋值。

 String[] anArray; // some magic logic anArray = new String[100]; for(int i = 0; i < anArray.length; i++){ // more magic logic to initialize the elements } 

另一个选项是Vector<>ArrayList<>如下所示:

 List anExpandableArray = new ArrayList(); // add String data anExpandaleArray.add("Foo"); anExpandaleArray.add("Bar"); 

当您发现自己想要创建相同类型的“更多变量”时,通常需要某种列表。 Java中有两种基本类型的“列表”:数组和List

数组:

 String[] people = new String[10]; // That gives you room for 10 people[0] = "female"; people[1] = "male"; // ... int n = 1; System.out.println("Person " + n + " is " + people[n]); 

List

 List people = new LinkedList(); // Expandable people.add("female"); people.add("male"); // ... int n = 1; System.out.println("Person " + n + " is " + people.get(n)); // Note difference -------------------------------^^^^^^^ 

当你事先知道将有多少arrays时,使用arrays是很好的。 当你不知道将有多少列表时,使用列表是很好的。

关于列表的注释:有一个接口List ,然后有多个不同的具体实现,具有不同的运行时性能特征( LinkedListArrayList等)。 这些是在java.util

只需使用这样的数组

 String[] people = new String[numofelements]; 

并初始化arrays

 for(int i = 0; i < people.length; i++){ people[i] = "whatever"; } 
 String[] persons = new String[101]; for (int i = 0; i < 101; i++) { if (i < 60) { String persons[i] = "female"; } else { String persons[i] = "male"; } }