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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19336202/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 16:13:47  来源:igfitidea点击:

How to create variables dynamically in Java?

javastring

提问by Andrei Vasilev

I need to create new variables Stringssuch that

我需要创建新的变量Strings,这样

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

This is what I tried

这是我试过的

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

Can anybody help me correct this code?

有人可以帮我更正这段代码吗?

采纳答案by MeBigFatGuy

A Map allows you to relate any key with any value. In this case, the key is the name of the variable, and the value is the value

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

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

回答by Little Child

You will need a String[]of some size that you can determine dynamically.
Then, assign values to the array elements.

您将需要一个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
}  

Another option is a Vector<>or ArrayList<>like so:

另一种选择是Vector<>ArrayList<>像这样:

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

回答by 06needhamt

Just Use an array like so

只需使用像这样的数组

String[] people = new String[numofelements];

And to initialise the array

并初始化数组

for(int i = 0; i < people.length; i++){
      people[i] = "whatever";
}

回答by fvrghl

You are close. If you store the the gender of each person in an array, you can do it like this:

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

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

Alternately, if a person is more than a gender, consider making a class Personthat holds a gender field, and then have an array of Persons. You would set the gender in a similar way.

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

回答by Christian Fries

You might use a Map<String,String>where the key is your "variable name" and the value is the value of that variable.

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

回答by user278064

String[] persons = new String[101];

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

回答by T.J. Crowder

When you find yourself wanting to create "more variables" of the same type, you usually want a list of some kind. There are two fundamental kinds of "lists" in Java: Arrays, and Lists.

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

An array:

数组:

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]);

A List:

List

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

Using an array is great when you know in advance how many there will be. Using a list is great when you don't know how many there will be.

当您提前知道将有多少个数组时,使用数组非常有用。当您不知道将有多少时,使用列表非常有用。

Note on lists: There's an interface, List, and then there are multiple different concrete implementations of it with different runtime performance characteristics (LinkedList, ArrayList, and so on). These are in java.util.

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