我如何用Java寫這個?
//js
const hello = {
foo: "bar",
test: "world",
name: "david"
}
我想要一個很長的物件,然后像hello[test]或hello[foo]
我聽說過hashmaps,但你只能創建一個空的,然后在其中添加元素。
我在 js 中有一個非常長的串列。如何將它們復制到 Java 中?一個一個地做 .put() 需要很長時間,我認為這不是有效的。
而且即使有人寫了一個腳本來uwu: "owo"變成hello.put("uwu", "owo");,在帶有一大塊hello.put()s 的代碼中也會很丑陋。
我也不想為此創建一個新檔案(它只有大約 34 行)并希望將其保留在代碼中。另外,因為我還有三個類似的檔案,每個檔案都有 20-40 個鍵和值,所以我不想創建三個只有 30 行的額外檔案。我也不想閱讀它們的復雜性。
哦,另外,我不會更改哈希圖,只是像常量一樣讀取資料。
總之,我可以在Java中為長串列做這樣的事情而不做.put()嗎?
public HashMap<String, String> hello = new HashMap<String, String>(
"foo": "bar",
"test": "world",
"name": "david",
"uwu": "owo"
);
并像這樣稱呼他們hello["name"]?我也不想要這個東西。
public HashMap<String, String> hello = new HashMap<String, String>();
hello.put("foo", "bar");
hello.put("test", "world");
hello.put("name", "david");
hello.put("uwu", "owo");
//for 25 more lines
public HashMap<String, String> hello2 = new HashMap<String, String>();
hello2.put("stuff", "thing");
//... for around 20 more lines
//repeat for 3 more hashmaps
uj5u.com熱心網友回復:
在現代 Java(14 及更高版本)中,您可以使用record:
record Hello(String foo, String test, String world) { }
并創建一個這樣的實體:
final Hello hello = new Hello("bar", "world", "david");
您可以訪問以下值:
System.out.print(hello.foo());
使用記錄的優點是您的資料是靜態型別的——您不能錯誤鍵入鍵,或忘記洗掉已從記錄中洗掉的鍵的使用。
uj5u.com熱心網友回復:
在 Java 14 及更高版本中,我建議使用記錄,如另一個答案中所述。這是最安全的,也可能是最有效的方法。
對于 Java 9 到 14,您可以使用Map.of("hello", "world", "foo", "bar");. 但是您可能無法超出一定數量的鍵/值對。
對于 java 8 及以下版本,或者如果您超過 Map.of 允許的引數數量,您別無選擇,只能創建一個空映射并一一放置鍵/值對。但請注意,性能不一定會更差。您當然可以使用可變數量的引數重新實作您自己的 Map.of 版本。
uj5u.com熱心網友回復:
由于您需要類似的常量,您可以將這些值保存在檔案中并從這些檔案中讀取。例如以 json 格式將資料保存在檔案中:
{
"foo": "bar",
"test": "world",
"name": "david"
}
然后將此檔案決議為Map.
public class Main {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(ClassLoader.getSystemResourceAsStream("constants.json"), Map.class);
map.forEach((k, v) -> System.out.println(k " -> " v));
}
}
此示例使用讀取檔案作為專案資源并使用ObjectMapper將 json 決議為 Map,但您可以使用任何其他工具來實作相同的效果。如果資料格式足夠簡單(字串鍵到字串值,沒有嵌套陣列、物件等),您可以將其保存為更簡單的格式并手動讀取、決議、添加到映射。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438558.html
