You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否通过参数为Java ArrayList命名?求多列表区分方案

解决Java中动态命名ArrayList的问题

Hey there! Great job diving into personal projects after just 2 months of learning Java—you're already building practical stuff, that's awesome.

First off, let's clear up a key point: you can't dynamically set variable names (like using a filename as an ArrayList's name) in Java. Java is a statically typed language, which means all variable names are fixed at compile time—you can't create new variable names on the fly based on runtime values like filenames.

But don't worry, there's a super clean alternative that solves your "distinguishing lists later" problem perfectly: use a Map<String, ArrayList<Vocabulary>>. Here's how it works:

  • The key of the map will be your filename (the string you already know how to get).
  • The value will be the ArrayList<Vocabulary> you created from that Excel file.

Example Code

// Initialize a HashMap to store filename -> vocabulary list pairs
Map<String, ArrayList<Vocabulary>> vocabularyMap = new HashMap<>();

// Let's say you've got your filename and populated list ready
String currentFileName = "english_vocab.xlsx"; // Replace with your filename logic
ArrayList<Vocabulary> currentVocabList = new ArrayList<>();

// ... Your code to read Excel and fill currentVocabList with Vocabulary objects ...

// Add the pair to the map
vocabularyMap.put(currentFileName, currentVocabList);

// Later, when you need to access the list for a specific file:
ArrayList<Vocabulary> targetVocabList = vocabularyMap.get("english_vocab.xlsx");
// Or iterate through all files and their lists:
for (Map.Entry<String, ArrayList<Vocabulary>> entry : vocabularyMap.entrySet()) {
    String fileName = entry.getKey();
    ArrayList<Vocabulary> vocabList = entry.getValue();
    // Do something with this file's list
}

This approach is way more scalable and maintainable than trying to hack dynamic variable names. You can easily add more files' lists, look up any list by its filename, or loop through all your datasets whenever you need to.

Another bonus: if you ever need to track extra info alongside the list (like file path, import timestamp), you could create a small wrapper class (e.g., VocabularyFile) that holds the filename and the list, then store instances of that class in a list instead—but for your current needs, the Map solution is straightforward and perfect.

内容的提问来源于stack exchange,提问作者Ecko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:09:00