Java ArrayList and iterators

Status
Not open for further replies.

stodge

Ars Tribunus Militum
1,907
I have an ArrayList, which I want to hold instances of a particular class, Player. I have two classes, Player and Team. So essentially, the Team class contains an ArrayList of players for that team.

teamPlayers = new ArrayList(numPlayers);

I can add players to the ArrayList using

code:<HR>
Code:
    public void addPlayer(Player newPlayer)
    {
	System.out.println("Adding player: " + newPlayer.getPlayerName());
	teamPlayers.add(newPlayer);
    }

But I want to iterate through the ArrayList and print out the names of all players that have been added.

Can I use an interator, or a list iterator? How would I do this? I thought of something like:

code:<HR>
Code:
    public void listPlayers()
    {
	Iterator iter = teamPlayers.iterator();
	while(iter.hasNext())
	    {
		System.out.println(iter.next().getPlayerName() + ", ");
	    }
    }

But this obviously doesn't work. Could someone offer a suggestion as to how to do this?

Thanks

(Damn this forum needs a preview button)
 

green_buddy

Wise, Aged Ars Veteran
126
Yes... in case you ever check this Thread again now that you've solved your problem... the idea is that the Iterator class deals with Objects of type java.lang.Object of which (I'm pretty sure) all classes are a part of by default. So by calling someIter.next() you will return yourself a class of type java.lang.Object because that's what the call to Iterator.next() returns. So you have to type-cast it to its known Object type... in this case of type Player.

You can also store multiple different objects of different Object types in a Vector, and then you can interate through the Vector and call instanceof on those objects to determine their actual class name.

code:<HR>
Code:
class Pitcher extends Player {...}
class Quarterback extends Player {...}

Pitcher exGiant = new Pitcher("Sean", "Estes");
Quarterback exNiner = new QuarterBack("Joe", "Montana");

Vector schtuff = new Vector();
schtuff.add(exGiant);
schtuff.add(exNiner);

...  // do a bunch of stuff

Iterator players = schtuff.iterator();

while (players.hasNext()) {
  Object aPlayer = players.next();
  if (aPlayer instanceof Pitcher) {

    // do something with the Pitcher

  } else if (aPlayer instanceof Quarterback) {

    // do something with the Quarterback

  } else if (aPlayer instanceof Player) {

    // do something with your player... which both Quarterbacks and
    // Pitchers are apart of, so if you have other non-distinct 
    // subtypes of Player you will be able to distinguish here.

  }
}

Hope some of that helps clarify what's going on.

-green
 
Status
Not open for further replies.