Results 1 to 4 of 4
  1. #1
    Join Date
    May 2008
    Posts
    8
    Rep Power
    0

    Question Convert Vector to Generic Array Cast Exception

    I have the following method:

    Java Code:
    public static <T> T[] vectorToArray(Vector<T> vector)
    {
        return (T[])vector.toArray(new Object[vector.size()]);
    }
    when I invoke it like this:

    Java Code:
    Vector<String> vector	 = new Vector<String>();
    String[] array = null;
    
    for(int i=0; i<10; i++)
    {
        vector.add("Entry" + i);
    }
    
    array = TypeUtilities.vectorToArray(vector);
    I get the following exception:

    Java Code:
    Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
    	at util.type.TypeUtilities.main(TypeUtilities.java:60)
    How can I get around this?

    Thank you for your time,
    Brandon

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    6

    Default

    right, because when you pass the new Object[] into the toArray() it creates an array of objects.

    Try,
    Java Code:
    public static <T> T[] vectorToArray(Vector<T> vector)
    {
        return (T[])vector.toArray(new T[vector.size()]);
    }
    ?

  3. #3
    Join Date
    May 2008
    Posts
    8
    Rep Power
    0

    Default

    that wont work, you cant instantiate a generic array.

  4. #4
    Join Date
    May 2008
    Posts
    8
    Rep Power
    0

    Default

    I came up with the following:

    Java Code:
    public static <T> T[] vectorToArray(Class<?> vectorClass, Vector<T> vector)
    {
        T[] array =  (T[]) Array.newInstance(vectorClass, vector.size());
    
        for(int i=0; i<array.length; i++)
        {
            array[i] = vector.elementAt(i);
        }
    
        return array;
    }
    BUT I would really like to remove the first parameter "Class<?> vectorClass" if at all possible to make the usage of the utility simplier. any ideas there?

Similar Threads

  1. Need Help with Class Cast Exception
    By soxfan714 in forum New To Java
    Replies: 2
    Last Post: 11-03-2011, 04:33 PM
  2. Convert a vector to a string array
    By orchid in forum New To Java
    Replies: 4
    Last Post: 02-24-2010, 02:31 AM
  3. How to convert the Vector object into an array?
    By tyang in forum New To Java
    Replies: 4
    Last Post: 02-08-2010, 08:00 AM
  4. How can I cast object to Vector?
    By batya in forum AWT / Swing
    Replies: 2
    Last Post: 11-19-2009, 05:02 PM
  5. class cast exception
    By venkatallu in forum New To Java
    Replies: 2
    Last Post: 09-02-2008, 09:50 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •