Results 1 to 7 of 7

Thread: Java - generic Array

  1. #1
    Join Date
    Jan 2007
    Beans
    Hidden!
    Distro
    Ubuntu

    Java - generic Array

    Since I cannot create generic array because of some type safety how can I then create an array for example in toArray() method?

  2. #2
    Join Date
    Jul 2008
    Location
    England
    Beans
    866

    Re: Java - generic Array

    Creating a generic array? Do you mean you want to create an array of a specific type, or do you want to create an array of all types? So for example do you want an array of Cat objects or an array of any type of Object.

    There are generic arrays that can be used for creating an array of a type. Look up ArrayList on the Java API.

    If you want an array to store Object 's of various types... why would you want to do this?

    Paul

  3. #3
    Join Date
    Aug 2007
    Location
    Novocastria, Australia
    Beans
    751
    Distro
    Ubuntu 9.04 Jaunty Jackalope

    Re: Java - generic Array

    I think LKjell means that you cannot create an array of say List<MyObj>. (which of course you can't - obvious type safety issues there). I'm not really sure what JKjell's actual question is though!

  4. #4
    Join Date
    Jul 2008
    Beans
    1,491

    Re: Java - generic Array

    Uhm?

    Code:
    public Type[] fromCollection(Collection<Type> collected) {
      /* see the docs at: http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collection.html */
      return collected.toArray(new Type[] {});
    }

  5. #5
    Join Date
    Jan 2007
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: Java - generic Array

    Say I have

    Code:
    public class list<E extends Comparable<E>> implements mylist<E> {
    
    ...
    
    public E[] toArray(E[] a) {
                E b[] = new E[size]; //Error: generic array
             ...
         }
    }

  6. #6
    Join Date
    Jul 2008
    Beans
    1,491

    Re: Java - generic Array

    Since your E is-a Comparable:

    Code:
    public E[] toArray(E[] a) {
      Comparable [] my_array = new Comparable[size]; // use supertype
      /* code */
      return (E[]) my_array; // cast to return type.
    }

  7. #7
    Join Date
    Jan 2007
    Beans
    Hidden!
    Distro
    Ubuntu

    Re: Java - generic Array

    Thanks Reiger I was pulling my hair when I was one error reading "Found E required E".

Bookmarks

Posting Permissions

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