25 October 2011

How to use toArray(T[] a) in ArrayList to make array of specific type?

WARNING!
I suspect that it's clumsy way to solve this problem and i guess you need google it, bin it (woops... i mean bing it)
for more professional solution,but if you want solution that works ... it should be helpful

So you have lovely ArrayList of specific type ... for example String  ( ArrayList<String> ) and you want convert to array of String but when you try using ArrayList.toArray() method then you receive array of objects in return which is not what you want,because you want ... Array of Strings (It sounds like good name for teenager music group of girls who are fun of Justin Bieder)... so what to do ?

During using IDE you discover that it suggests you to use toArray(T[] a) method,but question is how ?

You need to create array of type which you want have,so for my example will be String when length is determinated by size of arraylist (after finish adding all items).

(...)You created arraylist (      ArrayList<String> path = new ArrayList<String>(); and after added all stuff (...)
String[] patha = new String[path.size()];

and now you can use method
path.toArray(patha)

job done :)

below you have example:

public String[] chooseFiletoLoad() {
    ArrayList<String> path = new ArrayList<String>();

JFileChooser fc = new JFileChooser();
fc.setMultiSelectionEnabled(true);
int returnVal = fc.showOpenDialog(null);

if (returnVal == JFileChooser.APPROVE_OPTION) {
File[] file = fc.getSelectedFiles();
for(int i=0;i<file.length;i++){
  path.add(file[i].getPath());
}
    } else {
path = null;
}
String[] patha = new String[path.size()];

return path.toArray(patha);
}


I hope,it helps.