簡體   English   中英

如何在 JAVA 中使用字符串變量作為對象名稱?

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

我嘗試編寫一個具有寄存器部分的程序。 如果任何用戶想要創建一個新帳戶,那么程序會創建一個對象,那沒問題。 但是我沒有用戶的數量,所以我不能編碼到無限。每次程序應該為新用戶創建一個具有不同對象名稱(如 id)的對象。 對象名稱需要按順序形成。我試圖找到如何使用字符串變量作為對象名稱? 例如

User user001 = new User();

之后, user001 名稱應由 java 更改。 名稱應按順序為 user002,user003,如

你不能直接使用它。 但是你可以使用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 是將對象存儲在字符串標識符下的唯一方法。

編輯:根據以下評論進行修復。 謝謝你們 :)

編輯2:
要獲取始終按順序排列的用戶 ID,您有多種解決方案。

例如:
1. 您可以使用時間戳編號 - 這不會為您提供從0開始的列表,但無論如何它始終是有序的。 這是最簡單的解決方案。
2. 您需要將上次保存的 ID 存儲在某處(文件)並在您想要創建新用戶時始終檢索它。 這更復雜,但可以實現。 然后,您可以創建一個簡單的 ID 生成器來輕松選擇下一個值:
(偽代碼)

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

        return current;
    }
}

我在評論中做了一些解釋(這里最重要的部分是使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

地圖在這里工作。 但是對於更簡單的解決方案,只需使用List 使用get(int)按順序 (1, 2, 3, ... ) 訪問元素。 請注意,下面的第一個toString()方法就是這樣做的。 自動增量由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