Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Do Class Casts Work With Arrays?

  1. #1
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Do Class Casts Work With Arrays?

    Hello, everyone! I have recently run into a problem with a soccer team manager program I'm writing.

    Here's the code:

       public Player[] getPlayersThatMeetQuery(Player[] playersToTest)
       {
     
          ArrayList<Player> validPlayers = new ArrayList<Player>();
     
          for(Player p : playersToTest)
          {
     
             if(this.isMetBy(p)) //Ignore this method; something I've written; not the problem
             {
     
                validPlayers.add(p);
     
             }
          }
     
          return (Player[])validPlayers.toArray(); //Here's the error. Class casting with arrays?
     
       }

    And here's the error:

    Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LObjects.Player;
    	at Objects.PlayerQuery.getPlayersThatMeetQuery(PlayerQuery.java:193)
    	at Objects.PlayerQueryTest.main(PlayerQueryTest.java:36)
    Java Result: 1

    Don't worry about the Player class that I have created; the problem lies not in that class. Think of it as any other object.

    validPlayers is an ArrayList of players, yet when I try to class cast its toArray() method to a Player[], I get the above error. Does anyone see my error? Or is it illegal in Java to class cast with arrays?
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Do Class Casts Work With Arrays?

    You'll get a runtime exception if you try and cast an array of Object to an array of Player. That's why Collection provides the toArray(T[]) method as well. Try

    return validPlayers.toArray(new Player[0]);

  3. The Following User Says Thank You to pbrockway2 For This Useful Post:

    snowguy13 (February 19th, 2012)

  4. #3
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Do Class Casts Work With Arrays?

    Okay. Hm... That organization strikes me as odd...

    But, anyway, thank you!
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  5. #4
    Super Moderator Sean4u's Avatar
    Join Date
    Jul 2011
    Location
    Tavistock, UK
    Posts
    637
    Thanks
    5
    Thanked 103 Times in 93 Posts

    Default Re: Do Class Casts Work With Arrays?

    Quote Originally Posted by snowguy13 View Post
    Okay. Hm... That organization strikes me as odd...
    It is odd, it creates an object which is never used to prompt the method call to instantiate one just like it, only the right size. You can also write:
    return validPlayers.toArray(new Player[validPlayers.size()]);
    ... although if you're writing a lot of methods that take one collection of objects and returns a smaller collection of objects filtered from it, you could consider using the collections (Collection, Set, List etc) interface instead.

    Another alternative might be to return an Iterator which *doesn't* create a new collection (or array), but returns objects from the original collection skipping those that fail the filter. Here's an example, just for the sake of typing some Java:

    package com.javaprogrammingforums.domyhomework;
     
    import java.util.*;
     
    public class IteratorFilter
    {
      public static void main(String args[])
      {
        List<Integer> ints = new ArrayList<Integer>();
        for (int i = 0; i < 10; i++)
          ints.add(new Integer(i));
        OddIterator odds = new OddIterator(ints);
        while (odds.hasNext())
          System.out.println(odds.next());
      }
     
      static class OddIterator extends ProxyIterator<Integer>
      {
        public OddIterator(Collection<Integer> theIntegers)
        { super(theIntegers); }
        protected boolean isValid(Integer value)
        { return value % 2 == 1; } // odd?
      }
     
      static abstract class ProxyIterator<V> implements Iterator<V>
      {
        private final Iterator<V> backingIterator;
        private V next = null;
        protected ProxyIterator(Collection<V> collection)
        { backingIterator = collection.iterator(); }
        protected abstract boolean isValid(V value);
        public void remove()
        { throw new UnsupportedOperationException("No ProxyIterator.remove()"); }
        public boolean hasNext()
        {
          if (next != null)
            return true;
          while (backingIterator.hasNext())
          {
            next = backingIterator.next();
            if (isValid(next))
              return true;
          }
          next = null;
          return false;
        }
        public V next()
        {
          if (hasNext())
          {
            V wasNext = next;
            next = null;
            return wasNext;
          }
          // do whatever backing iterator does when finished
          // (throw a NoSuchElementException)
          return backingIterator.next();
        }
      }
    }

    ProxyIterator is a bit ugly / kludge-y, but it works as a filter on a collection of data without creating a new collection.

  6. The Following User Says Thank You to Sean4u For This Useful Post:

    snowguy13 (February 19th, 2012)

  7. #5
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Do Class Casts Work With Arrays?

    That's a very interesting idea. I'd have to read more into Iterators (though I think I get the gist of them). Thank you!
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  8. #6
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Do Class Casts Work With Arrays?

    Quote Originally Posted by Sean4u View Post
    It is odd
    I agree.

    You'd think that an ArrayList<Foo> would have commonsense enough to return a Foo[] when told to convert itself toArray(). But all knowledge of its Foo-ness is erased away at runtime. That's just how generics is (are?) in Java.

  9. #7
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Do Class Casts Work With Arrays?

    You'd think that an ArrayList<Foo> would have commonsense enough to return a Foo[] when told to convert itself toArray().
    That's exactly how I feel! At least the get() method returns the right object type.
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

  10. #8
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Do Class Casts Work With Arrays?

    It's instructive to (try and) create such a method yourself in order to see what happens. Something along the lines of:

    public class Foo<E> {
        private E data;
     
            // get() is fine...
        public E get() {return data;}
        public void set(E e) {data = e;}
     
            // ... but this one is not: "Cannot create a generic array of E"
        public E[] toArray() {return new E[]{data};}
    }

    Angelika Langer's excellent web site on generics has a discussion of what would go wrong.

  11. The Following User Says Thank You to pbrockway2 For This Useful Post:

    snowguy13 (February 23rd, 2012)

  12. #9
    Member snowguy13's Avatar
    Join Date
    Nov 2011
    Location
    In Hyrule enjoying a chat with Demise and Ganondorf
    Posts
    339
    My Mood
    Happy
    Thanks
    31
    Thanked 48 Times in 42 Posts

    Default Re: Do Class Casts Work With Arrays?

    Angelika Langer's excellent web site on generics has a discussion of what would go wrong.
    Ah, so it basically says that the traces of parameterized classes are lost declaring an instance of the class; if I declared an array of Foo<Integer>, the program still wouldn't be able to pick up an error if I tried to enter a Foo<String> in the array. In other words, the array only notices the Foo and doesn't pay enough attention to catch the differences in Foo's class parameter.

    Very interesting article, thanks pbrockway2!
    Use highlight tags to help others help you!

    [highlight=Java]Your prettily formatted code goes here[/highlight]

    Using these tags makes your code formatted, and helps everyone answer your questions more easily!




    Wanna hear something funny?

    Me too.

Similar Threads

  1. [SOLVED] Arrays being initialized from another class
    By Java Man 9000 in forum What's Wrong With My Code?
    Replies: 18
    Last Post: January 11th, 2012, 04:34 PM
  2. [Help] Problem with Class arrays, adding/editing and deleting
    By Grant_Searle in forum Object Oriented Programming
    Replies: 7
    Last Post: December 16th, 2011, 10:10 AM
  3. [SOLVED] Writing a program with arrays and class methods... PLEASE HELP?
    By syang in forum What's Wrong With My Code?
    Replies: 17
    Last Post: August 8th, 2011, 07:02 AM
  4. Retrieving arrays of java class inside C++ code
    By sattu in forum Java Native Interface
    Replies: 2
    Last Post: May 20th, 2011, 02:15 AM
  5. Issue with setting up different class with arrays
    By D-COD3R in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 4th, 2011, 06:09 PM