Is there away to generate Variables' names dynamically in Java?

后端 未结 10 2376
醉酒成梦
醉酒成梦 2020-11-28 14:46

Let\'s say that I need to generate variables to hold some input from the user (I don\'t know how many they are). Without using Array, ArrayList (an

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-28 15:23

    Without using Array, ArrayList (and other kind of lists and maps)

    Create files with these names. Hope that will work for your professor.

    Or use the Java Scripting API mentioned before:

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    
    engine.put("x", "hello"); // you can add any variable here
    // print global variable "x"
    engine.eval("println(x);");
    // the above line prints "hello"
    

    EDIT

    Seems like internally this will use Maps :) Same with Properties file, Preferences API, or DOM Trees (they are using Vectors). So if your professor is so picky, use files.

提交回复
热议问题