Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I dynamically name objects in Java?

Let's say I needed to make a series of String[] objects.

I know that if i wanted to make a string array called "test" to hold 3 Strings I could do

String[] test = new String[3];

But let's say I needed to make a series of these arrays and I wanted them to be named, 1,2, 3, 4, 5... etc. For however many I needed and I didn't know how many I'd need.

How do I achieve a similar effect to this:

for (int k=0; k=5; k++){ 
String[] k = new String[3];
}

Which would created 5 string arrays named 1 through 5. Basically I want to be able to create array objects with a name detemined by some other function. Why can't I seem to do this? Am I just being stupid?

like image 511
Sam Stern Avatar asked Apr 26 '10 03:04

Sam Stern


People also ask

How do you change a dynamic object name in Java?

The closest you will get in Java is: Map<String, String[]> map = new HashMap<String, String[]>(); for (int k=0; k=5; k++){ map. put(Integer. toString(k), new String[3]); } // now map.

How do you name an object in Java?

Objects/Variables: Java Naming convention specifies that instances and other variables must start with lowercase and if there are multiple words in the name, then you need to use Uppercase for starting letters for the words except for the starting word.

How do you make an object dynamic?

You can create custom dynamic objects by using the classes in the System. Dynamic namespace. For example, you can create an ExpandoObject and specify the members of that object at run time. You can also create your own type that inherits the DynamicObject class.


2 Answers

There aren't any "variable variables" (that is variables with variable names) in Java, but you can create Maps or Arrays to deal with your particular issue. When you encounter an issue that makes you think "I need my variables to change names dynamically" you should try and think "associative array". In Java, you get associative arrays using Maps.

That is, you can keep a List of your arrays, something like:

List<String[]> kList = new ArrayList<String[]>();
for(int k = 0; k < 5; k++){
   kList.add(new String[3]);
}

Or perhaps a little closer to what you're after, you can use a Map:

Map<Integer,String[]> kMap = new HashMap<Integer,String[]>();
for(int k = 0; k < 5; k++){
  kMap.put(k, new String[3]);
}
// access using kMap.get(0) etc..
like image 71
Mark Elliot Avatar answered Sep 19 '22 21:09

Mark Elliot


Others have already provided great answers, but just to cover all bases, Java does have array of arrays.

String[][] k = new String[5][3];
k[2][1] = "Hi!";

Now you don't have 5 variables named k1, k2, k3, k4, k5, each being a String[3]...

...but you do have an array of String[], k[0], k[1], k[2], k[3], k[4], each being a String[3].

like image 41
polygenelubricants Avatar answered Sep 21 '22 21:09

polygenelubricants