-2

I have instantiated multiple mutable variable:

SimpleStringBuffer a=new SimpleStringBuffer();
SimpleStringBuffer b=new SimpleStringBuffer();

I have done this 11 times, I know there is some way to avoid doing it using array or collections but I am not sure how. Can anyone help me with this?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
MR AND
  • 376
  • 7
  • 29

1 Answers1

1

You could use an array of SimpleStringBuffers:

SimpleStringBuffer arr = new SimpleStringBuffer[11];
for (int i = 0; i < arr.length; ++i) {
    arr[i] = new SimpleStringBuffer();
}

Or a List:

List<SimpleStringBuffer> list = new ArrayList<>(11);
for (int i = 0; i < 11; ++i) {
    list.add(new SimpleStringBuffer());
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • What should be done if I want to repeat the same procedure for the Map ? – MR AND May 18 '15 at 14:05
  • @user4230977 What Map? Can you elaborate the question please? – Mureinik May 18 '15 at 15:33
  • If i instantiate map in multiple places like this Map row1=new HashMap(); Map row2=new HashMap(); Map row3=new HashMap(); Map row4=new HashMap(); Is there a similar way to avoid multiple instantiation? – MR AND May 18 '15 at 15:41
  • 1
    @user4230977 the same technique will work for that too – Mureinik May 18 '15 at 17:45