简体   繁体   中英

Java - Name of Array Equals Value of String Variable

I have 10 array lists and a String variable. I have one function/method that allows the user to select one of the array lists to add to. Currently, that function changes the value of a string "chosen" to the value of the proper array list name.

Another function is started in which adding elements to the arraylist happens. However, I am struggling to come up with a solution on how to change which arraylist is being added to based upon what was selected by the user.

This code doesn't work but say it was:

chosen.add(whatUserEntered);

Normally you can put in the arrayList name and add .add(whateverTheUserIsEntering) and itll work fine.

So how can I have the name of an arrayList equal that of a String variable's value?

Here is an example using a Map to bind string names to lists. When you need to put things together at run time (as opposed to compile time, as you show with your example choosen.add(userEntered) ), you usually need to use a Map.

This works with strings read from a file (say to bind XML names to objects) or things like interpreters where you have to keep track of user variables by name.

public class SymbolTableExample
{
   public static void main(String[] args) {
      // Some array lists
      ArrayList<String> cats = new ArrayList<>();
      ArrayList<String> dogs = new ArrayList<>();
      ArrayList<String> beetles = new ArrayList<>();
      ArrayList<String> cows = new ArrayList<>();

      // Bind names to them
      Map<String,List<String>> binding = new HashMap<>();
      binding.put( "cats", cats );
      binding.put( "dogs", dogs );
      binding.put( "beetles", beetles );
      binding.put( "cows", cows );

      // Pretend the user enters some input here
      String userChoice = "cats";
      String userEntered = "flufy";
      binding.get( userChoice ).add( userEntered );

   }
}

Use a Map .

public interface Map<K,V>

You can use the method

V put(K key, V value)

to assign a value to a key, so you can set ArrayList s for different keys or add new ones..

Since you are using ArrayList s, you could make your make your Map like so:

Map<String, ArrayList<String>)> myArrays

Then, to add a value to an array with a given key, use

myArrays.get(userChosenArrayKey).add(whatUserEntered)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM