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

时间:2018-03-03 23:03:27

标签: java

我尝试编写一个具有寄存器部分的程序。如果任何用户想要创建一个新帐户,那么程序会创建一个对象,没关系。但是我没有得到用户的数量,所以我无法编写无限代码。每次程序都应该为新用户创建一个具有不同对象名称(如id)的对象。 对象名称需要按顺序形成。我试图找到如何使用字符串变量作为对象名称?例如

User user001 = new User();

之后,应该通过java更改user001名称。名称应按顺序排列 user002,user003 like

3 个答案:

答案 0 :(得分:1)

您不能直接使用它。但您可以使用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");

使用Collection API是您在字符串标识符下存储对象的唯一方法。

编辑:根据以下评论修复。谢谢你们:)

EDIT2:
要获得始终有序的用户ID,您可以获得多种解决方案。

例如:
 1.您可以使用时间戳编号 - 这不会为您提供从0开始的列表,但无论如何都会按顺序排列。这是最简单的解决方案 2.您需要在某处(文件)存储上次保存的ID,并在您想要创建新用户时始终检索它。这更复杂,但可以实现。然后,您可以创建一个简单的ID生成器来轻松选择下一个值:
(伪代码)

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

        return current;
    }
}

答案 1 :(得分:1)

我在评论中做了一些解释(这里最重要的部分是让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());
        }
    }
}

你得到的输出:

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

答案 2 :(得分:0)

地图可以在这里工作。但是,对于更简单的解决方案,只需使用List。使用get(int)按顺序(1,2,3,...)访问元素。请注意,下面的第一个toString()方法执行此操作。自动增量由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;
      }
   }
}