简体   繁体   English

如何在 JAVA 中使用字符串变量作为对象名称?

[英]How can i use string variable as an object name in JAVA?

I try to write a program which has a register part.我尝试编写一个具有寄存器部分的程序。 İf any user wants to create a new account then the program creates an object , thats ok .如果任何用户想要创建一个新帐户,那么程序会创建一个对象,那没问题。 But ı dont have got the number of user , so i can not code to infinite.Everytime the program should create an object with different object name (like an id) for new user.但是我没有用户的数量,所以我不能编码到无限。每次程序应该为新用户创建一个具有不同对象名称(如 id)的对象。 Object names need to be formed in order.I am trying to find how can i use string variable as an object name ?对象名称需要按顺序形成。我试图找到如何使用字符串变量作为对象名称? for example例如

User user001 = new User();

After that the user001 name should be changed by java .之后, user001 名称应由 java 更改。 The names should be in sequence user002,user003 like名称应按顺序为 user002,user003,如

You cannot use it directly.你不能直接使用它。 But you can use Map :但是你可以使用Map

Map<String, User> users = new HashMap<>();
users.put("user-001", new User(001));
users.put("user-00N", new User(XXX));
...
User currentProcessed = users.get("user-001");

Using Collection API is the only way in which you can store objects under string identifiers.使用 Collection API 是将对象存储在字符串标识符下的唯一方法。

EDIT: fixes based on comments below.编辑:根据以下评论进行修复。 Thanks guys :)谢谢你们 :)

EDIT2:编辑2:
To obtain userID's which are always in order you have serveral solutions.要获取始终按顺序排列的用户 ID,您有多种解决方案。

For example:例如:
1. You can use a timestamp number - this will not give you a list started from 0 , but it will always be in order no matter what. 1. 您可以使用时间戳编号 - 这不会为您提供从0开始的列表,但无论如何它始终是有序的。 And this is the simplest solution.这是最简单的解决方案。
2. You need to store last saved ID somewhere (file) and retrieve it always when you want to create new user. 2. 您需要将上次保存的 ID 存储在某处(文件)并在您想要创建新用户时始终检索它。 This is more complicated, but achievable.这更复杂,但可以实现。 then, you can create a simple ID generator to pick the next value easly:然后,您可以创建一个简单的 ID 生成器来轻松选择下一个值:
(In pseudo code) (伪代码)

class IdGenerator {
    public static int nextId() {
        int lastId = getIdFromFile();
        int current = ++lastId;
        store(current);

        return current;
    }
}

I made some explanations in the comments (The most important part here is to make counter static and to increment ID value with each creation of an instance of User:我在评论中做了一些解释(这里最重要的部分是使counter静态并在每次创建用户实例时增加ID值:

class User {
    private static int counter = 0; // static! - this is class member, it's common for all instances of Users
    private int ID = counter++; // new User has its own ID number that is incremented with each creation of new instance of User class
    private String name = "user" + ID; // here is unique name of each User

    public int getID() { // convenience method to show ID number
        return ID;
    }

    public String getName() { // convenience method to show name
        return name;
    }

    public String toString() { // String representation of User
        return name;
    }
}

public class MyClass {
    public static void main(String[] args) {
        Map<Integer, String> map = new LinkedHashMap<>(); // LinkedHashMap, just to make the output clear, Users will be stored in the order of adding them to Map

        for(int i = 0; i < 5; i++) { // Here you create 5 new Users and each has its own new ID
            User user = new User();
            map.put(user.getID(), user.getName()); // just to store new Users in a Map (key is ID number, value is user's name
        }

        for(Map.Entry<Integer, String> entry : map.entrySet()) { // this loop is just to print the results contained in Map to the console
            System.out.println(entry.getKey() + ": " + entry.getValue());
        }
    }
}

Output that you get:你得到的输出:

0: user0
1: user1
2: user2
3: user3
4: user4

Maps do work here.地图在这里工作。 However for a simpler solution just use a List .但是对于更简单的解决方案,只需使用List Access the elements in order (1, 2, 3, ... ) with get(int) .使用get(int)按顺序 (1, 2, 3, ... ) 访问元素。 Note the first toString() method below does this.请注意,下面的第一个toString()方法就是这样做的。 The auto-increment is provide by List which automatically increases the size of the list for you.自动增量由List提供,它会自动为您增加List的大小。

import java.util.ArrayList;
import java.util.Scanner;

public class UserRegistrar {

   private ArrayList<User> userList = new ArrayList<>();

   public static void main( String[] args ) {
      UserRegistrar users = new UserRegistrar();
      Scanner scan = new Scanner( System.in );
      for( ;; ) {
         System.out.println( "Enter a user name to register or a blank line to exit:" );
         System.out.print( "User name: " );
         String name = scan.nextLine().trim();
         if( name.isEmpty() ) break;
         User user = new User();
         user.setName( name );
         System.out.print( "User account no.: " );
         int acc = scan.nextInt();
         scan.nextLine();  // eat the new line
         user.setAccount( acc );
         users.addUser( user );
         System.out.println( users );
      }
   }

   public void addUser( User user ) {
      userList.add( user );
   }

   @Override
   public String toString() {
      StringBuilder stringBuilder = new StringBuilder();
      for( int i = 0; i < userList.size(); i++ ) {
         stringBuilder.append( i );
         stringBuilder.append( ": " );
         stringBuilder.append( userList.get( i ) );
         stringBuilder.append( '\n' );
      }
      return stringBuilder.toString();
   }


   public static class User {
      private String name;
      private int account;

      @Override
      public String toString() {
         return "User{" + "name=" + name + ", account=" + account + '}';
      }

      public String getName() {
         return name;
      }

      public void setName( String name ) {
         this.name = name;
      }

      public int getAccount() {
         return account;
      }

      public void setAccount( int account ) {
         this.account = account;
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM