0

I have a Person class

 public class Person 
        {
          private int age;
          private String first;
          private boolean valid;
        }

I have created an ArrayList of Person objects

ArrayList<Person> valid = new ArrayList<Person>();
        for(Person p : in)
        {
         valid.add(p);
        }

Now I want to convert this ArrayList to an array; I have tried this:

Person[] people = (Person[]) valid.toArray();

but this is throwing exception

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.net.Person;

4 Answers 4

6

you have to do something like this

Person[] people = valid.toArray(new Person[valid.size()]);
Sign up to request clarification or add additional context in comments.

4 Comments

sure it does:) glad I could help
@Antoniossss- have put 0 instead of valid.size() still working I don't understand How? Person[] people = valid.toArray(new Person[0]);
toArray will allocate new array if the one you will pass is not large enught to fit all contents. What happend with accepted answer ??
I have accepted don't know how it was changed, Anyway I had accepted again
1

You can't cast an Object[] to a Person[]. The toArray method needs to return the right type. There's an overloaded version of that method which takes an array of your type.

Person[] people = valid.toArray(new Person[valid.size()]);

http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#toArray(T[])

Comments

1

Can you try something like this:

Person[] people = valid.toArray(new Person[valid.size()]);

Comments

1

As you can see in the Javadocs, List.toArray() returns an Object[], so the list's generic type information is lost. That's why your cast doesn't work.

If you need to preserve the generic information, you must use the alternative toArray() method which takes an array of the desired type (because you could, for instance, want to turn a List<String> into a List<CharSequence> and so on).

All you need to do is pass an empty array of the desired type, e.g.:

list.toArray(new Person[]{});

However this is a little wasteful, as it forces the toArray() method to construct a new array of the appropriate size at runtime (via reflection). If instead you pass in an array that is already large enough, it will reuse that array avoiding the reflection and extra allocation.

list.toArray(new Person[list.size()]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.