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?