1

I'm trying to create an array of stringbuffers by:

StringBuffer[] rotor={"jndskfnjl","kjbsdbfkj","njkfdn"};

and it shows error "string cannot be converted to stringbuffer". but I can create an array of strings without any problem and I can create declare individual stringbuffers in a similar manner as strings without having to convert them.

Please tell me how I can make an array of stringbuffers.

3
  • Add the language tag, Java or? Commented Sep 15, 2015 at 3:15
  • What programming language are you using? Commented Sep 15, 2015 at 3:16
  • sorry, i added java tag now Commented Sep 15, 2015 at 3:18

2 Answers 2

4

You would have to go through and create the StringBuffer objects yourself. It's not an object like String, where you can create a new one without a constructor; you actually have to instantiate each occurrence.

StringBuffer[] rotor = {new StringBuffer("jndskfnjl"),
                        new StringBuffer("kjbsdbfkj"),
                        new StringBuffer("njkfdn")};
Sign up to request clarification or add additional context in comments.

Comments

2

You are creating an array of StringBuffer, It will expect list of objects of same type. It will not convert Strings to StringBuffer object. Because these two are completely different types in java. StringBuffer provides a constructor for creating object using string literals. You need to call them manually.

You can convert String array into StringBuffer array, iterating over a loop.

String array[] = new String[]{"jndskfnjl","kjbsdbfkj","njkfdn"};
StringBuffer buffers[] = new StringBuffer[array.length];
for (int i = 0; i<array.length; i++) {
  buffers[i] = new StringBuffer(array[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.