0

I am trying to understand the underlying difference between initializing Strings and StringBuffer The following code works fine. (al is an ArrayList<String>)

String[] sa = new String[al.size()];
System.arraycopy(al.toArray(), 0, sa, 0, al.size());

However when i use StringBuffer array it wont work.

StringBuffer[] sa = new StringBuffer[al.size()];
System.arraycopy(al.toArray(), 0, sa, 0, al.size());

It gives me following exception

java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at practice.ArrayListDemo.main(ArrayListDemo.java:34)

Can someone help me understand the logic/reason? It is not clear how string being immutable makes a difference.

1
  • Immutability has nothing to do with it. You're trying to mix array types. Commented Sep 20, 2014 at 23:22

2 Answers 2

3

How did you define al? Is it with the right type - StringBuffer? When I did the following there was no problem:

    List<StringBuffer> al = new ArrayList<StringBuffer>();
    StringBuffer[] sa = new StringBuffer[al.size()];
    System.arraycopy(al.toArray(), 0, sa, 0, al.size());
Sign up to request clarification or add additional context in comments.

1 Comment

no, i made a mistake. my arraylist was initialised with String.
2

Since you've declared al as an ArrayList<String>, we can safely assume that you've stored String objects in it.

But here

StringBuffer[] sa = new StringBuffer[al.size()];
System.arraycopy(al.toArray(), 0, sa, 0, al.size());

you're trying to copy String elements in a StringBuffer array. That doesn't work since String is not a subtype of StringBuffer.

2 Comments

yes, thanks a lot. i just understood the exception is thrown by the arraycopy method for type mismatch.
+1 This is the only answer that provides the actual reasoning behind the solution.

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.