This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Array to ArrayList Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array to ArrayList" Watch "Array to ArrayList" New topic
Author

Array to ArrayList

Cathy Song
Ranch Hand

Joined: Jul 01, 2003
Posts: 92
Hi All,

I have an array of Strings eg: String[] names. I would like to convert this to an ArrayList. I can write code to do it. But does anyone know of a method in the java API which already does this?

Thanks,
Cathy.
Weronpc
Greenhorn

Joined: Jun 12, 2004
Posts: 26
Hello Cathy,

private static final String names[] = {"Mike", "Cathy", "Nancy"};

List nome = new ArrayList( Arrays.asList( names ) );

By the way Cathy, I didn't test it out, but should work.

Mike
[ June 15, 2004: Message edited by: mike chi ]

1 + 1 = 10
Cathy Song
Ranch Hand

Joined: Jul 01, 2003
Posts: 92
Thanks Mike.
Leo Deegan
Greenhorn

Joined: Jun 15, 2004
Posts: 12
That should work. In fact, you can do this:

Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4458
    
    6

[B]That should work. In fact, you can do this:

[/B]

Yes, but Cathy wanted an ArrayList specifically. There's no guarantee that Arrays.asList() will return an instance of ArrayList. Your code is preferable though if there is no requirement for a specific type, just that it implements the List interface.


Junilu - [How to Ask Questions] [How to Answer Questions]
Leo Deegan
Greenhorn

Joined: Jun 15, 2004
Posts: 12
Ah, yes, good eye. I missed that detail in the question.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Array to ArrayList