JavaHolder
JavaHolder

Reputation: 7

How do I get two arrays into iterators to go step by step?

I am still new to java and have run into this problem.

I have two arrays of data each containing numeric details.

    static List<String> players1 = new ArrayList<String>(); 
    static List<String> players2 = new ArrayList<String>();
// Player 1 array plays player 2 array. List is always different on generation.

What I want to do is use both these strings in while loops to go through each of player1 array list ([4], [5] etc) strings and then get the player2 string ([0], [1] etc) then return back to the player 1 next string value. I had thought that the best way to do this was use iterators.

   Iterator it = players1.iterator();
   (it.hasNext()) {
   //get array string  
    // ++1?? 
    Iterator p2 = players2.iterator(); 
    (p2.hasNext()) {

       //get array string id.
       //return to next p1 string value.
    }

So I get one id from player1 array and then loops through player2 arrays and get one id from there and it returns to the next value of player1 iterator in the while loop and gets the next id from the player2 array and so on...

My question is, is this a good way to do this? Or is there an easily method I can cycle through the arrays step by step. If you have any examples of how to make this better or using another method then that would be great.

Thanks Java Holder.

Upvotes: 0

Views: 205

Answers (2)

Javier
Javier

Reputation: 12398

Iterator<String> it1 = players1.iterator();
Iterator<String> it2 = players2.iterator();
while (it1.hasNext()&&it2.hasNext()) {
 String id1 = it1.next();
 String id2 = it2.next();
}

After the loops ends

  • If it1.hasNext(), then players2 was shorter.
  • If it2.hasNext(), then players1 was shorter.
  • If !it1.hasNext()&&!it2.hasNext(), then both lists had the same size.

Upvotes: 0

dogbane
dogbane

Reputation: 274612

You don't need to use iterators here. Instead, use an enhanced for loop like this:

for (String player1 : players1) {
    for (String player2 : players2) {
        System.out.println("player1 is: " + player1 + ", player2 is: " + player2);
    }
}

Upvotes: 1

Related Questions