假设有一个名为“clients”的 Java 字符串数组列表。有什么方法可以将字符串添加到其中,以便它们保存由变量定义的自定义设置位置? 例如:(我知道代码不正确,但只是举个例子......)
class client{
public static int clientIdentifier = 6969;
public static String clientName = Peter;
ArrayList<String> clients = new ArrayList<String>();
}
In the main method:
clients.add(clientIdentifier, clientName);
这样 clientName 将 clientIdentifier 的值保存在数组中?
非常感谢!
最佳答案
是的,您可以将元素添加到 ArrayList 的特定索引处。
list.add(int index, E element)
但是,我相信 HashMap 更适合解决这个问题! 以下是如何使用 HashMap 来实现它。
HashMap<Integer, String> clients = new HashMap<>();
clients.put(clientIdentifier, clientName);
关于java - 有什么方法可以将一个条目添加到具有来自 int 变量的自定义位置的 Java 数组列表中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60102427/