Results 1 to 7 of 7
  1. #1
    vknehra10 is offline Member
    Join Date
    Dec 2016
    Posts
    99
    Rep Power
    0

    Default Why its printing randomly ?

    Java Code:
    import java.util.*;  
    class MapInterfaceExample{  
     public static void main(String args[]){  
      Map<Integer,String> map=new HashMap<Integer,String>();  
      map.put(100,"Amit");  
      map.put(101,"Vijay");  
      map.put(102,"Rahul");  
      for(Map.Entry m:map.entrySet()){  
       System.out.println(m.getKey()+" "+m.getValue());  
      }  
     }  
    }
    Output :

    102 Rahul
    100 Amit
    101 Vijay


    why it is print values randomly not sequently

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Why its printing randomly ?

    There is no order to a HashMap.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    SurfMan's Avatar
    SurfMan is online now Godlike
    Join Date
    Nov 2012
    Location
    The Netherlands
    Posts
    1,939
    Rep Power
    7

    Default Re: Why its printing randomly ?

    Use a LinkedHashMap if you want to retain order.
    "It's not fixed until you stop calling the problem weird and you understand what was wrong." - gimbal2 2013

  4. #4
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    381
    Rep Power
    4

    Default Re: Why its printing randomly ?

    ... or TreeMap if you want the values to be stored in a "natural" order (numbers or alphabet). You can re-define the order criteria for a TreeMap.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,532
    Rep Power
    24

    Default Re: Why its printing randomly ?

    It's the keys that are ordered in a TreeMap, not the values.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  6. #6
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    381
    Rep Power
    4

    Default Re: Why its printing randomly ?

    That’s what I meant, sorry for being fuzzy.

  7. #7
    vknehra10 is offline Member
    Join Date
    Dec 2016
    Posts
    99
    Rep Power
    0

    Default Re: Why its printing randomly ?

    can i ask mysql related questions on java-forums ?

Similar Threads

  1. EOFException randomly
    By elamre in forum Networking
    Replies: 2
    Last Post: 07-27-2012, 06:20 AM
  2. Replies: 0
    Last Post: 12-26-2011, 04:52 PM
  3. Picking randomly
    By AbdulAziz Bader in forum New To Java
    Replies: 17
    Last Post: 06-02-2010, 01:39 PM
  4. Randomly accessing files
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-12-2007, 11:46 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
  •