以char数组作为索引,以int作为值的结构

Structure with char array as index and int as value

本文关键字:结构 int 索引 char 数组      更新时间:2023-09-26

我正在翻译一个Javascript函数到Java,我有这个text变量下面的问题,如何在Java中声明和使用它:

Javascript:

var text={}; // Index will be several arrays, and value an integer
var word; // Will contain several chars, like a string
var myChar; // Will contain only one char
var value; // Will contain one integer
[...]
if(text[word+myChar]!=null)
{ // In this comparison, word is "hell", myChar is "o" and value is 1234
  text[word+myChar]=value; 
}

谢谢你的帮助

如果我们能看到你到目前为止(在Java中)所做的尝试将会非常有帮助。这可以帮助我们更好地理解你想要实现的目标。

以下是我收集到的建议:

  1. 看起来你正在创建字符串->整数(或类似的东西)的映射。这可以用Java中的HashMap<K,V>清楚地表示。它会说"将V类型的值的实例映射到K类型的键",K和V可以由你决定。有了这个,你可以创建一个HashMap<String, Integer>的实例,你可以在特定字符串键的哈希映射中获取/设置整数值。
  2. 您可以在Java中以类似的方式使用字符串连接(我假设这是在JS中使用word + myChar时发生的操作)。您将从中形成单个String对象。
  3. 对于HashMap,您可能想要使用containsKey(K key)get(K key),这取决于您是否想要查看键是否存在于映射中,或者该键在映射中的值是否为非空。这取决于问题的背景和你想要实现的目标。

下面是一个快速的(未测试的)示例,说明它可能是什么样子的:

import java.util.*;
public class WordIntMap {
    public static void main(String[] args) {
        HashMap<String, Integer> text = new HashMap<String, Integer>();
        String word = "hell";
        char myChar = 'o';
        int value = 1234;
        String key = word + myChar;
        if (text.get(key) != null) {
            text.put(key, value);
        }
    }
}
Map<String, Integer> text = new HashMap<String, Integer>();
...
if (text.containsKey(word+myChar)) {
  text.put(word+myChar, value);
}