如何用变量定义java对象名称?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19590265/
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 18:36:05  来源:igfitidea点击:

How to define a java object name with a variable?

java

提问by The Mather1

I need to create a large number of objects using a pattern of naming easily obtainable through a loop. Is there any way to have an object name be read from a variable, like this?

我需要使用可通过循环轻松获得的命名模式来创建大量对象。有没有办法从变量中读取对象名称,像这样?

String Var = "ObjectName";
ClassName Var = new ClassName();

I don't need the object to be assigned a variable name, merely to obtain the name from it at the time of assignment.

我不需要为对象分配变量名,只是在分配时从中获取名称。

采纳答案by slim

Your choice of words shows that you don't fully understand the way variables and objects work, and you need to fix that to get anywhere with Java.

您选择的词语表明您没有完全理解变量和对象的工作方式,您需要解决这个问题才能使用 Java。

If I write:

如果我写:

Item myItem = new Item();

I create a new object, andI define a variable which points to that object.

我创建了一个新对象,定义了一个指向该对象的变量。

The object does not have a name(it has an ID, which is a number assigned at runtime; most programmers can ignore it).

该对象没有名称(它有一个 ID,它是在运行时分配的一个数字;大多数程序员可以忽略它)。

The variable has a name, myItem. The variable points to the object. Later on, it might point to a different object. The variable might fall out of scope and cease to exist, while the object continues to exist.

该变量有一个名称myItem。变量指向对象。稍后,它可能指向不同的对象。变量可能超出范围并停止存在,而对象继续存在。

You might say, "that's not important. If I say the 'name of the object', I mean 'the name of the variable pointing to the object'."

您可能会说,“这并不重要。如果我说‘对象的名称’,我的意思是‘指向该对象的变量的名称’。”

But it is important, because lots of objects will be pointed to by more than one variable:

但这很重要,因为许多对象将被多个变量指向:

Item myItem = new Item();
Item yourItem = myItem;
// both variables point to the same object. Neither variable is "more" the
// owner of the object than the other.

... and lots of objects won't be pointed to directly by a variable.

...并且很多对象不会被变量直接指向。

myList.append(new Item()); 
// you can't get at this new object using a direct variable.


In Java (and most mainstream languages), you can't create variable names at runtime. The only variable names that exist, are ones that are literally in the source code.

在 Java(和大多数主流语言)中,您不能在运行时创建变量名。唯一存在的变量名称是源代码中的字面意思

So there's nothing that works like this:

所以没有什么是这样的:

int number = 1;
Cell cell$number = new Cell(); // can't be done!
Cell currentCell = cell1; 

Nor can you access variables by name, based on runtime data. So there's nothing that works like this:

您也不能根据运行时数据按名称访问变量。所以没有什么是这样的:

Cell cell1 = ...;
int number = 1;
Cell currentCell = cell$number; // can't be done!

This is a good thing because it lets the compiler validate certain things about your code.

这是一件好事,因为它可以让编译器验证有关您代码的某些内容。

In some languages you could possibly achieve something like this using eval() -- but you should run a mile from it!

在某些语言中,您可以使用 eval() 实现类似的功能——但您应该离它一英里!

This is a hint that if you're writing code like:

这是一个提示,如果您正在编写如下代码:

 Cell cell0 = new Cell(...);
 Cell cell1 = new Cell(...);
 ...
 Cell cell99 = new Cell(...);

... then you're doing something wrong. It may work, but it scales badly. There is no way to put this into a loop. (Don't worry - most of us hit this issue when we began programming).

……那你做错了什么。它可能有效,但扩展性很差。没有办法将其放入循环中。(别担心 - 我们大多数人在开始编程时都会遇到这个问题)。

If, instead you'd used an array:

如果,相反,您使用了一个数组:

 Cell[] cells = new Cell[];
 cells[0] = new Cell(...);
 cells[1] = new Cell(...);
 ...
 cells[99] = new Cell(...);

Then you could use a loop instead:

然后你可以改用循环:

 for(int i = 0; i<100; i++) {
     cells[i] = new Cell(...);
 } 

An array is the simplest of "collection" objects. There are also Sets, Lists, Maps, and a host of more advanced collections, to suit most needs.

数组是最简单的“集合”对象。还有集合、列表、地图和许多更高级的集合,以满足大多数需求。

You seem to want to store and access objects using strings as a key. The way to do this is using a Map.

您似乎想使用字符串作为键来存储和访问对象。这样做的方法是使用地图。

Map<String,Cell> myMap = new TreeMap<String,Cell>();

myMap.put("AA", new Cell(...));
myMap.put("AB", new Cell(...));

...

Cell currentCell = myMap.get("AA");

Mapis an interface. TreeMapis just one class that provides an implementation of the Mapinterface. Read up on the various implementations of Mapprovided by the standard JRE.

Map是一个接口TreeMap只是一个提供Map接口实现的类。阅读Map标准 JRE 提供的各种实现。

The key doesn't have to be a String. Anything that implements equals()can be used as a key.

密钥不必是String. 任何实现的东西equals()都可以用作密钥。

Using this:

使用这个:

for(char c = 'A'; c <= 'L'; c++) {
   for(char d = 'A'; d<= 'L'; d++) {
       myMap.put("" + c + d, new Cell(...));
   }
}

However, since you've said you want a grid, it's probably better to work with a 2D array, and translate the numeric coordinates to and from a lettered grid-reference whenever you need to. Google for "2D array Java", and you'll find plenty of examples.

但是,由于您已经说过想要一个网格,因此最好使用 2D 数组,并在需要时将数字坐标与带字母的网格参考相互转换。谷歌搜索“2D array Java”,你会发现很多例子。

Cell[][] cells = new Cell[12][12];
for(int x=0; x<12; x++) {
   for(int y=0; y<12; y++) {
       Cell cell = new Cell();
       cell.setName( "" + ('A' + x) + ('A' + y)); // perhaps
       cells[x][y] = cell;
   }
}

Beyond the standard JRE, there are plenty of other implementations of Map. For example, Spring provides DefaultRedisMap, in which the objects are stored in a Redis database.

除了标准的 JRE,还有很多其他的Map. 例如,Spring 提供了 DefaultRedisMap,其中的对象存储在 Redis 数据库中。

More generally - you have asked a very basic question here. You should read the chapter on the Collections APIin any decent Java book.

更一般地说 - 你在这里问了一个非常基本的问题。您应该阅读任何体面的 Java 书籍中有关Collections API的章节。

回答by David MacNeil

Easily obtainable? Have you looked into Arrays? If you want to use Strings then a string array will suffice, there are also char and int arrays.

容易获得吗?你研究过数组吗?如果您想使用字符串,那么字符串数组就足够了,还有 char 和 int 数组。

    String[] myStringArray = new String{"hello", "world"};
    int[] myIntArray = new int{1, 2, 3, 6};

I suggest you read up on arrays and their uses, I believe it may solve your problem.

我建议您阅读数组及其用途,我相信它可以解决您的问题。

回答by NickJ

It's not at all clear what you want. If you want to look up objects by name, you could use a Map

根本不清楚你想要什么。如果要按名称查找对象,可以使用 Map

Example:

例子:

Map<String, Object> map = new HashMap<String, Object>();

String objectName = ...// get name of object
Object object = ...// get object
map.put(objectName, object);

Then it can be retrieved:

然后它可以被检索:

Object obj = map.get(objectName);