2

I have inherited a Java program which I need to change. In one part of the code, I see I have created over 1000 String variables such as:

String field01  
String field02  
...  
String field1000

I want to make a for loop to set all of the mentioned variables to "", but I am having issues with building a correct format for the for loop.

How do I create field+(i) in the for loop to set field01 to "" and the rest?

6
  • In Java there are no dynamic variables. You can't loop through a set of distinct variable names like that unfortunately. Commented Sep 23, 2015 at 0:09
  • 1
    @skandigraun You can fake it using reflection, but it's still bad design that should be refactored instead of worked-around. Commented Sep 23, 2015 at 0:09
  • 2
    You "could" use reflection, but you'd just be propagating the problem (and generally making it worse). A better solution would be to replace the String field{n} with an array or List Commented Sep 23, 2015 at 0:10
  • @MadProgrammer, if it's variables (not fields) reflection won't help. Commented Sep 23, 2015 at 0:35
  • @TagirValeev This is true, but I'd discourage the idea anyway Commented Sep 23, 2015 at 0:38

5 Answers 5

2

A for loop... Well, you could make this an array, but there's not really any way to make this into a for loop without an array.

Here's an example with one:

String[] test = new String[1000];
for (int number; numer < 1000; number++){
     test[number] = "";
}
Sign up to request clarification or add additional context in comments.

Comments

2

You have to use Reflection for doing the same.

class Test {
  String field1  
  String field2  
  ...  
  String field1000
}



public class FieldTest {

 public static void main(String args[]) {
    Test t = new Test();
    Class cls = t.getClass();

     for(int i=0 ; i<=1000; i++){
        Field f1 = cls.getField("field"+i);
       f1.set(t, "");
     }
  }
}

Comments

1

You can't really do this in Java. An alternative is to make a String array where the index of the array is the number of the variable that you want. So field01 would be stored in your string array at index 1.

Comments

0

First, create an array. Second, use Arrays.fill:

String[] fields = new String[1000];
Arrays.fill(fields, "");

Later you can access or modify individual variables by indices like fields[index].

Creating 1000 variables with similar names is not how people program in Java.

Comments

0

I know it is not the exact answer, but may help you.or you will need to use reflection.

Map<String, String> container = new HashMap<String, String>();
   for (int i = 0; i <1000; i++) {
   container.put("field"+ i, "\"\" ");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.