Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-7039126

for..each iterator does not iterate through ArrayList

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Not an Issue
    • Icon: P4 P4
    • None
    • 6u24
    • tools
    • x86
    • windows_xp

      FULL PRODUCT VERSION :


      ADDITIONAL OS VERSION INFORMATION :
      Microsoft Windows XP [Version 5.1.2600]
      (C) Copyright 1985-2001 Microsoft Corp.



      EXTRA RELEVANT SYSTEM CONFIGURATION :
      Eclipse 3.6.2
      TextPad 5.3.1

      A DESCRIPTION OF THE PROBLEM :
      'm trying to transverse an ArrayList with a for..each loop, but an error was reported through Eclipse IDE:
      can only iterate over an array or an instance of java.lang.Iterable. See Source code marked A.

      In another instance it was noted that the for..each loop was returning an unexpected String results, notwithstanding that I have provided a toString() method for the superclass (Employee).


      NOTES
      1. According to the Java API for 1.6, ArrayList implements Iterable<E> - http://download.oracle.com/javase/6/docs/api.
      2. Java Notes, For-each loop at http://leepoint.net/notes-java/flow/loops/foreach.html.

      References
      Core Java Vol. I 8th Ed ISBN-13 978-0-13-235476-9 Pg. 198.


      REGRESSION. Last worked in version 6u24

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should be possible to iterate through a Collection.
      ACTUAL -
      Source code A - An error message was displayed.
      can only iterate over an array or an instance of java.lang.Iterable

      Source code B
      [LEmployee;@190d11
      [LEmployee;@190d11
      [LEmployee;@190d11
      Press any key to continue . . .

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      Source code A - An error message was displayed.
      can only iterate over an array or an instance of java.lang.Iterable

      Source code B - unreadable string

      REPRODUCIBILITY :
      This bug can be reproduced always.

      ---------- BEGIN SOURCE ----------
      Source Code A
      package poker;

      import java.awt.Image;
      import java.io.BufferedInputStream;
      import java.io.File;
      import java.io.FileInputStream;
      import java.io.IOException;
      import java.io.InputStream;
      import java.util.*;
      import javax.imageio.ImageIO;

      import org.apache.log4j.BasicConfigurator;
      import org.apache.log4j.Logger;
      public class Poker {

      public static final short MAX_CARDS_IN_DECK = 52;
      public static final short MAX_SUITS_IN_DECK = 4;
      public static final short MAX_RANK_IN_DECK = 13;
      public static final short MAX_PLAYERS_PER_TABLE = 5;
      public static final short MAX_GAMES = 1;
      //TODO: implement concurrent games and UI at a later stage.

      public static double amountOnTable;
      public static final String CURRENCY_SYMBOL = "€";

      public static void main(String[] args) {

      BasicConfigurator.configure();

      readIcons();

      boolean shuffled = true;
      getCards(shuffled);

      Player playerOne = new Player("Player One", 10000.00);
      playerOne.getCardFromDealer(getTopCard());
      playerOne.getCardFromDealer(getTopCard());
      if (playerOne.betAmount(100.00) == false) {System.out.println("WARNING: Player tried to bet " + CURRENCY_SYMBOL + "100.00, whilst the balance available is " + CURRENCY_SYMBOL + playerOne.getBalance());}


      Player playerTwo = new Player("Player Two", 10000.0);
      playerTwo.getCardFromDealer(getTopCard());
      playerTwo.getCardFromDealer(getTopCard());
      Double _amountforPlayerTwo = 10000.0;
      if (playerTwo.betAmount(_amountforPlayerTwo) == false) {System.out.println("WARNING: Player tried to bet " + CURRENCY_SYMBOL + _amountforPlayerTwo + ", whilst the balance available is " + CURRENCY_SYMBOL + playerTwo.getBalance());}

      Player playerThree = new Player("Player Three", 10000.0);
      playerThree.getCardFromDealer(getTopCard());
      playerThree.getCardFromDealer(getTopCard());
      if (playerThree.betAmount(100.00) == false) {System.out.println("WARNING: Player tried to bet " + CURRENCY_SYMBOL + "100.00, whilst the balance available is " + CURRENCY_SYMBOL + playerThree.getBalance());}

      Player playerFour = new Player("Player Four", 10000.0);
      playerFour.getCardFromDealer(getTopCard());
      playerFour.getCardFromDealer(getTopCard());
      if (playerFour.betAmount(100.00) == false) {System.out.println("WARNING: Player tried to bet " + CURRENCY_SYMBOL + "100.00, whilst the balance available is " + CURRENCY_SYMBOL + playerFour.getBalance());}

      Player playerFive = new Player("Player Five", 10000.0);
      playerFive.getCardFromDealer(getTopCard());
      playerFive.getCardFromDealer(getTopCard());
      if (playerFive.betAmount(100.00) == false) {System.out.println("WARNING: Player tried to bet " + CURRENCY_SYMBOL + "100.00, whilst the balance available is " + CURRENCY_SYMBOL + playerFive.getBalance());}

      for (int iBettingRounds = 0; iBettingRounds < 3; iBettingRounds++) {
      playerOne.getCardFromDealer(getTopCard());
      playerOne.betAmount(100.00);

      playerTwo.getCardFromDealer(getTopCard());
      playerTwo.betAmount(100.00);

      playerThree.getCardFromDealer(getTopCard());
      playerThree.betAmount(100.00);

      playerFour.getCardFromDealer(getTopCard());
      playerFour.betAmount(100.00);

      playerFive.getCardFromDealer(getTopCard());
      playerFive.betAmount(100.00);
      }

      System.out.println(playerOne);
      System.out.println(playerTwo);
      System.out.println(playerThree);
      System.out.println(playerFour);
      System.out.println(playerFive);

      System.out.println("Cards held by dealer:");
      for (int i = 0; i < deckOfCards.size(); i++) { System.out.println((i + 1) +"." + deckOfCards.get(i));}

      }
      private static void getCards (boolean _shuffled) {
      short iCount = 0;
      for (short suit = 1; suit <= MAX_SUITS_IN_DECK; suit++){
      for (short rank = 1; rank <= MAX_RANK_IN_DECK; rank++) {
      deckOfCards.add(iCount, new Card(suit, rank));
      iCount++;
      }}

      if (_shuffled == true){Collections.shuffle(deckOfCards, new Random());}

      }

      private static Card getTopCard() {
      Card _cardRemoved = deckOfCards.get(1);
      deckOfCards.remove(1);
      return _cardRemoved;
      }

      private static void readIcons(){

           String _filename;

           //read icons
           Image _image = null;
           File _file = null;
           InputStream _is = null;
           for (int i = 1; i < MAX_CARDS_IN_DECK + 1; i++) {
           try {

           /* Security information: filenames should not be altered manually by an Administrator, and,
           should be available within the same directory where the source code runs. */

           if (i < 10) {_filename = "0" + Integer.toString(i);}
           else {_filename = Integer.toString(i);}

           String _temp = _filename;
           _filename = _temp + ".GIF";

           //TODO: Relative path might change when implementing?
           _filename = System.getProperty("user.dir") + "\\img\\" + _filename;

           _file = new File(_filename);

           //read from an input stream
           _is = new BufferedInputStream (new FileInputStream(_filename));

           _image = ImageIO.read(_is);
           if (_file.exists()) {
           CardIcons.add(_image);
           //_log.debug(_filename + " loaded.");
           }
           }
           catch (IOException e) { _log.debug(e.getMessage()); }
           }
          }

      @SuppressWarnings("unused")
      //TODO: write ranking rules
      private static ArrayList<Player> getWinner(ArrayList<Player> _players) {

      ArrayList<Player> _winners = null;
      _winners.addAll(_players);
      short _handRanking = 0;
      /*TODO: 1. Player.setRanking(_ranking) for each of the players:
      Ranking
      for hand #

      1. Straight flush. Five cards in sequence all of the same suit.
      2. Four of a kind. Four cards of the same rank i.e. two pairs.
      3. Full house. Three cards of the same rank, and, a pair of cards with the same rank.
      4. Flush. Five cards of the same suit.
      5. Straight. Five cards in sequence, not necessarily of the same suit.
      6. Three of a kind. Three cards of the same rank.
      7. Two pair. Two pairs of cards, each having the same rank. Higher ranks win.
      8. One pair. One pair of cards with the same rank.
      9. High card. Cards in order of their rank.

      Further information at http://en.wikipedia.org/wiki/Poker_hands.
      */

      /*TODO: If two or more players have equal high ranking, then players get to split the pot, hence, add both players to the winning
      ArrayList and return the ArrayList.
      */
      for (int i = 0; i < _players.size(); i++) {
      /* TODO: DEBUG: FIX problem with iterating over _players??
      for (Card _card: _players.get(i)) {

      * Can only iterate over an array or an instance of java.lang.Iterable.
      * Posted question at
      * 1. http://www.eclipse.org/forums/index.php?t=msg&goto=666922&S=8d4d6d31ec3bab3a6790bbd95a61dfce#msg_666922, and, at
      * 2.http://www.coderanch.com/t/535513/java/java/Error-only-iterate-over-array#2429030.
      }
      }
      NOTE: This is a show-stopper for this toy-project.
      */
      return _winners;
      }

      }
      private static ArrayList<Image> CardIcons = new ArrayList<Image>();
      private static ArrayList<Card> deckOfCards = new ArrayList<Card>();
      private static final Logger _log = Logger.getLogger(Poker.class);


      /* References
      * ----------
      * Texas Hold'em rules are used throughout the game.
      * Information about poker at http://en.wikipedia.org/wiki/Poker.
      * List of poker hands at http://en.wikipedia.org/wiki/Poker_hands.
      * Rules for Texas Hold'Em at http://en.wikipedia.org/wiki/Texas_hold_&#39;em. This will be implemented at a later stage.
      * Steve Badger, How to Play Poker at http://www.playwinningpoker.com/articles/how-to-play-poker.
      * Graphics to be implemented at a later stage.
      */
      }

      ------------------------------------------------------------------------------------------------
      Source Code B
      ------------------------------------------------------------------------------------------------

      import java.util.*;

      /**
       * This program demonstrates inheritance.
       * @version 1.21 2004-02-21
       * @author Cay Horstmann
       */
      public class ManagerTest
      {
         public static void main(String[] args)
         {
            // construct a Manager object
            Manager boss = new Manager("Carl Cracker", 80000, 1987, 12, 15);
            boss.setBonus(5000);

            Employee[] staff = new Employee[3];

            // fill the staff array with Manager and Employee objects

            staff[0] = boss;
            staff[1] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
            staff[2] = new Employee("Tommy Tester", 40000, 1990, 3, 15);
            staff[1].setBuddy(staff[1]);

            // print out information about all Employee objects
            for (Employee e : staff)
             // System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
             System.out.println(staff.toString());
         }
      }

      class Employee
      {
         public Employee(String n, double s, int year, int month, int day)
         {
            name = n;
            salary = s;
            GregorianCalendar calendar = new GregorianCalendar(year, month - 1, day);
            hireDay = calendar.getTime();
         }

         public String getName()
         {
            return name;
         }

         public double getSalary()
         {
            return salary;
         }

         public Date getHireDay()
         {
            return hireDay;
         }


         public Employee setBuddy(Employee aBuddy)
         {
      this.buddy = aBuddy;
      return buddy;
         }

         public void raiseSalary(double byPercent)
         {
            double raise = salary * byPercent / 100;
            salary += raise;
         }

         public String toString() {
      return "Employee[name=" + name + ",salary="+ salary + ",hire day=" + hireDay + "]";
      }

         private String name;
         private double salary;
         private Date hireDay;
         private Employee buddy;
      }

      class Manager extends Employee
      {
         /**
          * @param n the employee's name
          * @param s the salary
          * @param year the hire year
          * @param month the hire month
          * @param day the hire day
          */
         public Manager(String n, double s, int year, int month, int day)
         {
            super(n, s, year, month, day);
            bonus = 0;
         }

         public double getSalary()
         {
            double baseSalary = super.getSalary();
            return baseSalary + bonus;
         }


         public Manager setBuddy(Manager aBuddy)
         {
      this.buddy = aBuddy;
      return buddy;
         }

         public void setBonus(double b)
         {
            bonus = b;
         }



         private double bonus;
         private Manager buddy;
      }



      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      None found to date.

            Unassigned Unassigned
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            0 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: