Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to dinamically populate a String array?

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i can query this pupils table to obtain an ArrayList with their email adresses
from javamail api the method to send to more then one adress at the same time is:


how can i dinamically populate the para[] String array?
 
Efrain Morales
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you could simply use something like String [] para = myArrayList.toArray(); , as long as your ArrayList is declared as <String> type.

Doing it without that <String> type could also work, but I don't think it's safe to do it.

You could also do it manually by using

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that worked nicely

thanks a lot!
 
Siva Masilamani
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I would recommend to use instanceof operator before you cast array list element to String.

E.g.

 
John de Michele
Rancher
Posts: 600
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or, just use an ArrayList<String>.

John.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Efrain Morales wrote:I think you could simply use something like String [] para = myArrayList.toArray(); , as long as your ArrayList is declared as <String> type.

Not quite; the array returned by ArrayList.toArray() is always an Object[]. When you try to cast that to String[] you will get a ClassCastException. The following will work though:
As the Javadoc of Collection.toArray(T[]) says, it will make sure the runtime type of the returned array is the same as the type of the array argument.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic