Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 help with ArrayList.toArray();
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
facultyofmusic




PostPosted: Wed Aug 19, 2009 4:27 pm   Post subject: help with ArrayList.toArray();

I'm trying something with the ArrayList, and encountered a problem. Using generics, I've made an ArrayList with type String. So I'm expecting i can safely operate Strings with the arraylist. But soon I found that the toArray() method of the array list returns Object[], not String[] (I didn't try casting because I figured that I couldn't cast from an Object to String anyways). I looked in the Javadoc for ArrayList. It had two toArray methods. One that I used, and one that I don't really understand. Can someone show me how to use the other one? here's the Javadoc for arrayList that I used:

http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html

Here's the code that I wrote:

Java:

import java.util.*;
public class Test {
String [] array;
ArrayList <String> arrayList = new ArrayList <String> ();

    public static void main (String args []){
        Test t = new Test ();
        t.start ();
    }

    public void start (){
        // first put 3 elements into the array
        arrayList.add ("Homer ");
        arrayList.add ("likes ");
        arrayList.add ("doughnuts.");

        // arrayList to array
        array = arrayList.toArray(); // this is the problem.
        System.out.println(array);
    }
}
Sponsor
Sponsor
Sponsor
sponsor
[Gandalf]




PostPosted: Wed Aug 19, 2009 4:34 pm   Post subject: Re: help with ArrayList.toArray();

facultyofmusic @ 2009-08-19, 4:27 pm wrote:
I didn't try casting because I figured that I couldn't cast from an Object to String anyways

But, you sure can!

Anyway, the other toArray() method returns the ArrayList as an array of whatever the type of each element in the passed array is. So, for example:
code:
myList.toArray(new String[0]);

Would return an array of Strings that are retrieved from myList.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 2 Posts ]
Jump to:   


Style:  
Search: