Results 1 to 2 of 2
  1. #1
    coolman50544 is offline Member
    Join Date
    Apr 2014
    Miami, FL
    Rep Power

    Question For each loop confusing

    Java Code:
    public static void main(String[] args) {
           HashMap<Integer, String> stuff = new HashMap<>();     
           stuff.put(1, "Book");
           stuff.put(2, "Pancake");
           stuff.put(3, "Waffle");
           for(Map.Entry thing : stuff.entrySet())
               System.out.println(thing.getKey() + ": " + thing.getValue());         
    So I make a HashMap which is pretty simple. My book showed me how I would print all the values in a format showing their key a ": " and the the actual value. What I don't understand is why the type element for the for each loop is the interface, Map.Entry. How is this possible? It's an interface, so it doesn't make much sense to me. Also, why is stuff.entrySet() method necessary?

  2. #2
    jim829 is online now Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: For each loop confusing

    First, about interfaces. Class instances may be assigned to any interface types which they implement. The preferred way to initiate a HashMap is the following:

    Java Code:
    Map<Integer, String> stuff = new HashMap<>();
    For lists it is

    Java Code:
    List<Integer> list = new ArrayList<>();
    If you do it that way, then later on you could change ArrayList to LinkedList and not have to change any other code.

    The only time that won't work or be of use is when the implementation of the interface offers additional methods not defined in the interface. But the Map.Entry interface is implemented privately inside the HashMap implementation. So you are returned an instance. You can also iterate thru the values like this:

    Java Code:
    for (String str : stuff.values()) {
    Last edited by jim829; 06-15-2014 at 05:35 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. confusing name repite
    By willemjav in forum Advanced Java
    Replies: 19
    Last Post: 12-12-2013, 02:51 PM
  2. Confusing Error
    By CODinacup in forum New To Java
    Replies: 1
    Last Post: 10-02-2012, 05:44 AM
  3. A very confusing question
    By JohnPringle83 in forum New To Java
    Replies: 3
    Last Post: 05-08-2011, 08:29 AM
  4. confusing ques
    By rok0016 in forum New To Java
    Replies: 6
    Last Post: 07-15-2010, 07:07 PM
  5. Confusing with Frameworks
    By hisouka in forum New To Java
    Replies: 0
    Last Post: 08-05-2008, 06:52 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts