Created
August 3, 2010 18:56
-
-
Save sgharms/506916 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Can anyone explain a bit of Java Collections syntax to me? | |
1. I created a class of things call JavaCard (a flash card) that extends Card. | |
1. There is also a JavaCardDeck, subclassed from CardDeck. | |
1. CardDeck possesses an ArrayList called 'cards' as an iVar. The ArrayList is declared as possessing type <Card>. I think that this is good polymorphism. | |
1. One loads JavaCardDeck, which effectively wraps the ArrayList, with JavaCard | |
I want to be able to get a "normal" array out of a JavaCardDeck instance. Thus: | |
aJavaCardDeck.getCards // should return an array of Cards, | |
// makes sense given the way I defined the <> | |
Here's the code that's tricky: | |
public Object[] getCards(){ | |
return cards.toArray(); | |
} | |
From a runtime safety POV, this makes perfect sense. Put everything into an Array of Objects. | |
Good idea. But *I* know, and each heap-being knows that it is effectively a JavaCard -- | |
or a Card at the very least -- I would like to "cast" that array on the way out. | |
It appears that the way to do this is in ArrayLsit: | |
public Object[] toArray(Object[] a) [Source](http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#toArray(java.lang.Object[])) | |
Looks promising! | |
Returns an array containing all of the elements in this list in the correct order; the runtime | |
type of the returned array is that of the specified array. If the list fits in the specified | |
array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the | |
specified array and the size of this list. | |
OK, great. So I tried getting the syntax right a couple of times but eventually found this invocation ([Source](http://download-llnw.oracle.com/javase/tutorial/collections/interfaces/collection.html)): | |
String[] a = c.toArray(new String[0]); | |
So here's my question. How did one derive: | |
String[] a = c.toArray(new String[0]); | |
from | |
public Object[] toArray(Object[] a); | |
? | |
I could completely see replacing "Object" with "String...": | |
public String[] toArray(String[] a) | |
But where does that zeroth-index come in? I just don't get it and I want to understand what this syntax mean. What's going on with *new String[0]*? | |
Thanks! | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment