Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Whats the difference between ..( Vector class )  RSS feed

 
Zkr Ryz
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all.
could any please explain me what's the difference between:
public void copyInto(Object[] anArray)
and

Object[] toArray()
Can I use this kind of typecast?
MyClass [] mc = ( MyClass [] ) vector.toArray();
???
Thanks
 
Frank Carver
Sheriff
Posts: 6920
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No you can't use the cast approach. toArray returns an object of class 'Object[]' whch can't be cast to 'MyClass[]', even if all the elements in it are actually MyClass objects.
The recommended way to do this is to use the version of toArray which takes a 'prototype':

This allows your code to tell the 'toArray' method what sort of array to create, which I believe is what you need.
 
Zkr Ryz
Ranch Hand
Posts: 187
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot frank.
I was using something like:

MyClass [] store = new MyClass [ vector.size() ];
for( int i = 0 ; i < store.length ; i++){
store[i] = vector.get(i);
}
But something told me this was a bad approach, I check out the Collection API an found th toArray() and copyInto(Object []) but for some reason never saw toArray( Object array[] ) method.
Well, I appreciate your help, and soon I'll post a new question, I don't know on what issue, but I will.


 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!