0

Is there a way to do this? I'm trying to call an array using a String of it's name

  public static void main(String [] args)
  {
    int [] temp=new int [1];
    temp[0]=1;
      String a="temp";

      System.out.println(a[0]);
     }
  • 5
    This is not possible in Java because Java is not a dynamic language. This is what `Map<>` data structures are for. This is also an example of an [XY Problem](http://xyproblem.info). If you would explain what you _really_ want to accomplish we might be able to help, but with such a bare bones example all we can say is "You can't do that in Java". I suggest you flesh out the question with a meaningful example, or risk attracting downvotes. – Jim Garrison Mar 09 '16 at 22:11
  • Similarly: [Assigning variables with dynamic names in Java](http://stackoverflow.com/questions/6729605/assigning-variables-with-dynamic-names-in-java). – azurefrog Mar 09 '16 at 22:13
  • Possible duplicate of [Get variable by name from a String](http://stackoverflow.com/questions/13298823/get-variable-by-name-from-a-string) – fabian Mar 09 '16 at 22:19

2 Answers2

0

NO this is not possible as the variable names cannot be declared dynamically in Java.

Rishi
  • 1,163
  • 7
  • 12
0

Try using a HashMap it is similar to what your looking for.

public static void main(String... args) {
    HashMap<String, Integer> test = new HashMap<String, Integer>();
    test.put("Temp", 1);
    test.put("Temp2", 2);

    System.out.println(test.get("Temp")); // returns one

    HashMap<Integer, String> test2 = new HashMap<Integer, String>();
    test2.put(1, "Temp");
    test2.put(2, "Temp2");

    System.out.println(test2.get(1)); // returns one
}

This is an interesting question if you want to know the differences between Map vs HashMap.

What is the difference between the HashMap and Map objects in Java?

Community
  • 1
  • 1
Monroy
  • 420
  • 5
  • 19