HashMaps and Arrays

I am extracting data from MYSQL in a result set. The values are then stored in HashMap. The total count of rows would be around 650 - 700 approx. I get a Array out of Bound exception.
(Note: I have a HashMap array- HashMap hm[] = new HashMap[800]; )
Any one to comment on this. If you need any more information.. let me know...
-Krish

PMJain wrote:
Why do you allocate a HashMap[]?
you would need a single instance of HashMap to be populated with some key/value pairs
where key might be your primary key and the value could be the object with the data from a single record.My guess is that Cubby was turning each result set row into a Map that mapped the column name to the row's value. Meh.

Similar Messages

  • Hashmap and array list problems

    This is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go from here. Any guidance would be very welcomed.
    We were given code that used just an Array lisThis is an assignment I have to do and I do NOT expect anyone to do the coding for me. I am just looking for some direction as I have no clue where to go next. Any guidance would be very welcomed.
    We were given code and told to "Modify the MailServer so that it uses a HashMap to store MailItems. The keys to the HashMap should be the names of the recipients, and each value should be an ArrayList containing all the MailItems stored for that recipient. " Originally it was just an ArrayList named messages. There is also a MailClient and MailItem class.
    I think I can post the messages using the HashMap now, but can't test it. I get a compiler error saying else without if even though I have an if statement. Even if I can compile, I need to make sure I am on the right track with the getNextMailItem method. It is the one I am stuck on and if I can get it to work, I can probably modify the other methods.
    I would really appreciate feedback on that one method.
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.Iterator;
    public class MailServer
         // Storage for the arbitrary number of messages to be stored
         // on the server.
         private HashMap messages;
         private ArrayList list;
         private MailItem item;
          * Construct a mail server.
         public MailServer()
             messages = new HashMap();
             list = new ArrayList();
          * Return the next message for who. Return null if there
          * are none.
          * @param who The user requesting their next message.
         public MailItem getNextMailItem(String who)
              Iterator it = list.iterator();
              while(it.hasNext())
                MailItem item = (MailItem)it.next();
                if(messages.containsKey(who));
                    return item;
               else
                   return null;
          * Add the given message to the message list.
          * @param item The mail item to be stored on the server.
         public void post(String name, MailItem item)
             if(messages.containsKey(name))
                    list = (ArrayList) messages.get(name);
                    else {
                        list = new ArrayList();
                        list.add(item);
                        messages.put(name, list);
    }[                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    The way I understand this is that MailItems are stored in per user ArrayLists, and that the ArrayLists are stored in the HashMap, and use the username as a key,
    HashMap messages = new HashMap();
    //ArrayList userMailItems = new ArrayList(); this should not be declared here, only the messages mapso given a User name, you need to get the list of mail items for that user out of the hashMap, and then return the next MailItem from the list. So given that, you don't even need to Iterate over the list:
    public MailItem getNextMailItem(String who)
    ArrayList list = (ArrayList)messages.get(who);
    if(list == null || list.size() == 0)
    return null;
    //now we get the next item from the list, we can call remove, since it returns the object we are removing.
    MailItem item = (MailItem)list.remove(0);
    return item;
    }

  • All the xml and arrays are getting NULL Problem

    Hello guys
    I am working on a project which uses xml loading, e4x and array manipulation extensively, and it was going good but now I got stuck on a strange problem.  Whole code was fine and application was working and responding in a desired way, but then mystourisly it stopped working and started to retun NULL values to almost all the actionscript (internal) Arrays and XML varibales.
    Now Whenever i load xml file and assign the loaded values to internal xml variables, internal values get only NULL instead of data.
    Same is the situation with Arrays, I created some components in mxml, and when i passed them to arrays by reference, code gets compiled successfully, but again Array has only null values [that code was working fine too]
    I am wondering if Adobe Flex did a silenced update or something similar and it is the result of that things !
    I am using Adobe Flex 3.2 with SDK 3.3 on windows Vista Ultimate.
    Please check this attached project, Import it and see if you face the same problem
    Thanks
    Link to Problem Project
    http://isolatedperson.googlepages.com/problemXperiment.zip
    Problem Screenshot
    http://isolatedperson.googlepages.com/xmlissue.JPG

    Use HTTPService to load the data. You'll have fewer problems.
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application creationComplete="dataSvc.send();"
      xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
         <mx:Script>
              <![CDATA[
                import mx.collections.XMLListCollection;
                import mx.rpc.events.ResultEvent;
                [Bindable] private var xlc:XMLListCollection;
                   private function loadXML(evt:ResultEvent):void{
                    xlc =  new XMLListCollection(evt.result.individual.@id as XMLList);
              ]]>
         </mx:Script>
         <mx:HTTPService resultFormat="e4x" result="loadXML(event)" url="alirazaTree.xml" id="dataSvc"/>
         <mx:ComboBox id="cbx" dataProvider="{xlc}"/>
    </mx:Application>

  • Difference Between HashMap and HashTable

    Difference Between HashMap and HashTable
    Please explain with an example

    I have a situation in Java Collection and i am not
    able to figure a good solution. I am scared about the
    performance and memory that wil be used
    I have 5 List objects with thousands and thousands of
    records in it. The List is populated by a database
    query using jdbcTemplate which return like 200,000
    records
    Each record is identified by POLICY_ID. They may be
    List with multiple records for a POLICY_ID
    I want to extract each POLICY_ID from all the 5 List
    and make a single List object for each POLICY_ID and
    for each List and pass it to a print job which will
    print the data for a POLICY_ID
    Example
    Let say we have POLICY_ID = 15432
    List1 has one record for 15432
    List2 has one record for 15432
    List3 has one record for 15432
    List4 has three record for 15432
    List5 has three record for 15432
    From the 200,000 records in List1 i want to generate
    a seperate list with 1 record for policy id 15432 and
    let name is Listperpolicy
    after this logic we have
    Listperpolicy1
    Listperpolicy2
    Listperpolicy3
    Listperpolicy4
    Listperpolicy5
    call print job ( Listperpolicy1, Listperpolicy2,
    Listperpolicy3, Listperpolicy4, Listperpolicy5)
    Please let me know
    Thanks a Lotttttttttdon't worry about performance until you've got a working application. second-guessing what the performance bottlenecks will be is futile

  • Loops and Arrays help

    Hi,
    I'm a freshman in college and new to java. I am completely lost and really need help with a current assignment. Here are the instructions given by my teacher...
    Building on provided code:
    Loops and Arrays
    Tracking Sales
    Files Main.java and Sales.java contain a Java application that prompts for and reads in the sales for each of 5 salespeople in a company. Files Main.java and Sales.java can be found here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Main.java
    and here http://www.ecst.csuchico.edu/~amk/foo/csci111/labs/lab6N/Sales.java It then prints out the id and amount of sales for each salesperson and the total sales. Study the code, then compile and run the program to see how it works. Now modify the program as follows:
    1. (1 pts) Compute and print the average sale. (You can compute this directly from the total; no new loop is necessary.)
    2. (2 pts) Find and print the maximum sale. Print both the id of the salesperson with the max sale and the amount of the sale, e.g., "Salesperson 3 had the highest sale with $4500." Note that you don't necessarily need another loop for this; you can get it in the same loop where the values are read and the sum is computed.
    3. (2 pts) Do the same for the minimum sale.
    4. (6 pts) After the list, sum, average, max and min have been printed, ask the user to enter a value. Then print the id of each salesperson who exceeded that amount, and the amount of their sales. Also print the total number of salespeople whose sales exceeded the value entered.
    5. (2 pts) The salespeople are objecting to having an id of 0-no one wants that designation. Modify your program so that the ids run from 1-5 instead of 0-4. Do not modify the array-just make the information for salesperson 1 reside in array location 0, and so on.
    6. (8 pts) Instead of always reading in 5 sales amounts, allow the user to provide the number of sales people and then create an array that is just the right size. The program can then proceed as before. You should do this two ways:
    1. at the beginning ask the user (via a prompt) for the number of sales people and then create the new array
    2. you should also allow the user to input this as a program argument (which indicates a new Constructor and hence changes to both Main and Sales). You may want to see some notes.
    7. (4 pts) Create javadocs and an object model for the lab
    You should organize your code so that it is easily readable and provides appropriate methods for appropriate tasks. Generally, variables should have local (method) scope if not needed by multiple methods. If many methods need a variable, it should be an Instance Variable so you do not have to pass it around to methods.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this.
    I'm not asking for someone to do this assignment for me...I'm just hoping there is someone out there patient and kind enough to maybe give me a step by step of what to do or how to get started, because I am completely lost from the beginning of #1 in the instructions.
    Any help would be much appreciated! Thank you!
    Message was edited by:
    Scott_010
    Message was edited by:
    Scott_010

    First ask the person who gave this asignment as to why do you require two classes for this , you can have only the Sales.java class with main method in it . Anyways.
    Let Main.java have a main method which instanciates a public class Sales and calls a method named say readVal() in Sales class.
    In the readVal method of sales class define two arrays i.e ids and sales. Start prompting the user for inputting the id and sales and with user inputting values keep storing it in the respective arrays .. Limit this reading to just 5 i.e only 5 salesPerson.
    Once both the arrays are populated, call another method of Sales class which will be used for all computations and output passing both the arrays.
    In this new method say Compute() , read values from array and keep calculating total,average and whatever you want by adding steps in just this loop. You can do this in readval method too after reading the values but lets keep the calculation part seperate from input.
    You must create the working application and a web page to provide the applications information (i.e., a page with links to the source code, the javadoc and an object model) to get full credit. You can use the example.html's from the last two labs to help you remember how to do this. I think this is ur personal stuff , but if you want to use web page , you probably will require to use servlet to read values from the html form passed to the server.

  • Challeging Traversal of Vector and Array

    Hi there ! I would like to render the values of this Vector and Array . How do I print it out to the browser ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while (rset.next())
    aRow = new String[numColumns];
    for (int i=0; i < numColumns; i++){
    aRow[i] = rset.getString(i+1);
    allRows.addElement(aRow);
    return allRows;
    }

    Hi there !
    Thanks for your help but I managed to get it working. For references purposes, I`ll post it here.
    My problem now is this :-
    How can I issue another SQL statement and store the results in the same array?
    Pls note . One Sql per table so, that`s the issue ?
    Can someone help with a followup code ?
    try
    ResultSet rset = stmt.executeQuery(myQuery);
    System.out.println(" Finish Execute Query !!! ");
    /* Array Contruction */
    int numColumns = rset.getMetaData().getColumnCount();
    while(rset.next())
    // for every record instance aRow
    aRow = new String[numColumns];
    // store in aRow the values of the record
    for(int i=0;i<numColumns;i++)
    aRow[i] = rset.getString(i+1);
    //When aRow is full store it in the vector
    allRows.addElement(aRow);
    // when the rset finished print all the Vector
    for(int i=0;i<allRows.size();i++)
    // get returns a String[]
    String[] tmpRow = (String[])allRows.get(i);
    for(int j=0;j<tmpRow.length;j++)
    out.print(tmpRow[j]+" ");
    out.println("");
    }

  • NXT Flatten to String Not Working with Clusters and Arrays

    Hello,
    My name is Joshua and I am from the FIRST Tech Challenge Team 4318, Green Machine. We are trying to write a program that will write to a configuration file and read it back. The idea is that we will be able to write to a config file from our computer that will be read by our autonomous program when it runs. This will define what the autonomous program does.
    The easiest way to do this seems to be flattening a data structure to a string, saving it to a file, and then reading back and unflattening it. The issue is that the flatten to string and unflatten from string VIs don't seem to work with arrays and clusters on the NXT. It does work when running on the computer. We've tried arrays, clusters, clusters in arrays and arrays in clusters, none seem to work. Thinking it was something to do with reading the string from a file, we tried bypassing the file functionality, still not working. It does work with basic data types though, such as strings and numbers.
    No error is thrown from what we can tell. All you get is a blank data structure out of the unflatten VI.
    The program attached is a test program I've been working on to get this functionality to work. It will display the hex content of what is going into the file, coming out of the file, and then the resulting data from the unflatten string, as well as any errors that have been thrown. The data type we are using simulates what we would like to store. There is also a file length in and out counter. The out file is a little larger because the NXT write file VI adds a new line character on to the end (thus the use of the strip white space VI). This character was corrupting even basic data types saved to file.
    I would like to know if there is a problem with what we are doing, or if it is simply not possible to flatten arrays on the NXT. Please ask if you have any questions about the code. Thank you in advanced!
    Joshua
    Attachments:
    ReadableTest.vi ‏20 KB

    Hi jfireball,
    This is a very interesting situation. Take a look at what kbbersch said. I also urge you to post in the FTC Forums. You posted your question to the general LabVIEW forums, but by posting to the FTC Forums, you will have access to others that are using the NXT hardware.
    David B.
    Applications Engineer
    National Instruments

  • Iterate through HashMap and .....

    Hi friends,
    I have a HashMap with say following entries..
    (ad_key1 , value1)
    (ad_key2 , value2)
    (ad_key3 , value3)
    (ad_key4 , value4)
    (hk_key1 , value1)
    (hk_key2 , value2)
    (hk_key3 , value3)
    (hk_key4 , value4)
    Now my requirement is that i have to iterate through the hashmap and get all the values for the keys starting with ad_ , and not just that whils storing it in some other place remove that ad_ part and store the remaining. so removing the other part od_... and storing it is fine, i will do that.
    But the problem is how do i iterate through the HashMap in a way that i retreive first key then check if it is starting with ad_ , then retreive second key and check that whether it is starting with ad_ and so on .
    please do help,
    thanks in advance

    import java.util.Iterator;
    import java.util.HashMap;
         public class IteratorExample
              public static void main(String args[])
                   HashMap hashMap = new HashMap(); // Constructs a new empty HashMap
                   hashMap.put( "One", new Integer(1) ); // adding value into HashMap
                   hashMap.put( "Two", new Integer(2) );
                   hashMap.put( "Three", new Integer(3) );
                   System.out.println("Retriving all keys from the HashMap");
                   //     retrive iterator from keySet of the hashmap
                   Iterator iterator = hashMap.keySet().iterator();
                   while( iterator. hasNext() )
                        System.out.println( iterator.next() );
         }

  • Strange behaviour of "And array Elements"

    If u connect an empty boolean array to "And Array Elements" function, The output is "True" !. Is this correct?. Is there something wrong ?. Please Help.

    Hi J.A.C
    This is correct.This is an explanation I've found: "This behavior is intentiional, and stems from elementary Boolean logic. The Boolean algebra primitives are analogous to numeric operations are integers. Just as the identity element for addition is 0, and for multiplication, 1; the identity for Boolean OR is FALSE, and for AND, TRUE. For example, x^0 == 1; that is, x times itself zero times is by definition 1. For the same reason boolean x ANDed with itself zero times is TRUE."
    If this is not acceptable for your application, then just use the "Array Size" VI first to check if you've an empty Array (Array size=0) and then you can pass or not the array to the "And Array Elements" function.
    Hope this helps.
    Luca
    Regards,
    Luca

  • Problems launching Object Manager and Array Manager in SSGD 4.20.983

    Hi,
    I have just installed SSGD 4.20.983 in a server which is running Solaris 10. The language of this server is Spanish.
    When I access to the webtop, I 'm not be able to launch the applications Object Manager and Array Manager.
    When I try to launch them, in the details box appears "Contrase�a" and them the timeout expires. Contrase�a is the same that password in Spanish.
    Anyone can help me?
    Regards,
    Diego

    Do you have any logfiles which look like : execpePID_error.log?
    These files should contain more information.
    Also take a look at the following section of the Administration Guide: [http://docs.sun.com/source/820-6689/chapter4.html#d0e21816]
    Especially the part '+Increasing the Log Output+'
    - Remold

  • Performance of System.arraycopy and Arrays.fill

    I have some code where I call a function about 1,000,000 times. That function has to allocate a small array (around 15 elements). It would be much cheaper if the client could just allocate the array one single time outside of the function.
    Unfortunately, the function requires the array to have all of its elements set to null. With C++, I would be able to memset the contents of the array to null. In Java, the only methods I have available to me are System.arraycopy() and Arrays.fill().
    Apparently, Arrays.fill() is just a brain-dead loop. It costs more for Arrays.fill() to set the elements to null than it does to allocate a new array. (I'm ignoring possible garbage collection overhead).
    System.arraycopy is a native call (that apparently uses memcpy). Even with the JNI overhead, System.arraycopy runs faster than Arrays.fill(). Unfortunately, it's still slower to call System.arraycopy() than it is to just allocate a new array.
    So, the crux of the problem is that the heap allocations are too slow, and the existing means for bulk setting the elements of an array are even slower. Why doesn't the virtual machine have explicit support for both System.arraycopy() and Arrays.fill() so that they are performed with ultra-efficient memsets and memcpys and sans the method call and JNI overhead? I.E. something along the lines of two new JVM instructions - aarraycpy/aarrayset (and all of their primitive brethern).
    God bless,
    -Toby Reyelts

    A newly allocated array begins its life with null in its elements. There is no need to fill it with null.
    As Michael already stated, I'm not redundantly resetting all of the elements to null. Here's some code that demonstrates my point. You'll have to replace my PerfTimer with your own high performance timer. (i.e. sun.misc.Perf or whatever) Also note that the reason I'm only allocating half the array size in allocTest is to more accurately model my problem. The size of the array I need to allocate is variable. If I allocate the array outside of the function, I'll have to allocate it at a maximum. If I allocate inside the function, I can allocate it at exactly the right size.import java.util.*;
    public class AllocTest {
      private static final int count = 100000;
      public static void main( String[] args ) {
        for ( int i = 0; i < 10; ++i ) {
          allocTest();
        double allocStartTime = PerfTimer.time();
        allocTest();
        double allocTime = PerfTimer.time() - allocStartTime;
        for ( int i = 0; i < 10; ++i ) {
          copyTest();
        double copyStartTime = PerfTimer.time();
        copyTest();
        double copyTime = PerfTimer.time() - copyStartTime;
        for ( int i = 0; i < 10; ++i ) {
          fillTest();
        double fillStartTime = PerfTimer.time();
        fillTest();
        double fillTime = PerfTimer.time() - fillStartTime;
        System.out.println( "AllocTime (ms): " + allocTime / PerfTimer.freq() * 1000 );
        System.out.println( "CopyTime (ms): " + copyTime / PerfTimer.freq() * 1000 );
        System.out.println( "FillTime (ms): " + fillTime / PerfTimer.freq() * 1000 );
      private static void allocTest() {
        for ( int i = 0; i < count; ++i ) {
          Object[] objects = new Object[ 8 ];
      private static void copyTest() {
        Object[] objects = new Object[ 15 ];
        Object[] emptyArray = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          System.arraycopy( emptyArray, 0, objects, 0, emptyArray.length );
      private static void fillTest() {
        Object[] objects = new Object[ 15 ];
        for ( int i = 0; i < count; ++i ) {
          Arrays.fill( objects, null );
    }I getH:\>java -cp . AllocTest
    AllocTime (ms): 9.749283777686829
    CopyTime (ms): 13.276827082771694
    FillTime (ms): 16.581995756443906So, to restate my point, all of these times are too slow just to perform a reset of all of the elements of an array. Since AllocTime actually represents dynamic heap allocation its number is good for what it does, but it's far too slow for simply resetting the elements of the array.
    CopyTime is far too slow for what it does. It should be much faster, because it should essentially resolve to an inline memmove. The reason it is so slow is because there is a lot of call overhead to get to the function that does the actual copy, and that function ends up not being an optimized memmove. Even so, one on one, System.arraycopy() still beats heap allocation. (Not reflected directly in the times above, but if you rerun the test with equal array sizes, CopyTime will be lower than AllocTime).
    FillTime is unbelievably slow, because it is a simple Java loop. FillTime should be the fastest, because it is the simplest operation and should resolve to an inline memset. Fills should run in single-digit nanosecond times.
    God bless,
    -Toby Reyelts

  • Append variable and array items after a record array search

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

  • HashMaps and Sorting issue.

    Hey,
    I was wondering what the most effective method of doing the following was:
    I have some directories which are a collection of <id, reference to either a directory or a file> sets. The file objects contain a hashmap which has some information about the file. I want to sort the directory the file is in, by the values in the hashmap of the file.
    Originally I had the directory as a hashmap, with the id the key and the reference to the directory or file the value. The plan was to put the values.getHashMap.values() in an array, and sort it. However, I'm not quite sure this would work. I'm also no longer sure if a hashmap is the most effective way of doing this.
    Any ideas? Should I elaborate? Should I get rid of hashmap all together in this case?
    Thanks,
    -S

    First call the entrySet() method of the Map and you'll get a Set of EntrySet objects. The EntrySet object contains the key and the value, so it's those you want to sort. You can make a List or an array of those EntrySet objects quite easily, and then with a suitable Comparator you can sort that List or array in the right order.

  • Help with HashMap and Collections

    Hey everyone,
    I am currently writing a program that makes use of HashMap, which I am not at all familiar with. I looked it up in some books and some websites, but it seems everyone does something different every time so I need some guidance. My program is to take Inventory Item objects that have an name and an inventory number and store them in a HashMap. Originally I had them stored in an Array but now it's gonna be in a HashMap. This also uses some Java GUI elements so bear with me.
    Ok, first here is my code for my Item object:
    public class Item{
        private String number;
        private String name;
        public Item(String number, String name) {
              this.number = number;
              this.name = name;
          @Override
          public String toString() {
              return "#"+number+"  N:"+name;
    }And this is what I got so far for my Inventory GUI:
    import java.util.HashMap;
    import java.util.Iterator;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JScrollPane;
    public class InventoryGUI {
         //private static Item[] item = new Item[10];
         HashMap hash = new HashMap();
         private static int count = 0;
         public static void main(String[] args) {
              JFrame gui = new JFrame("Project 2 GUI");
              gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              JPanel inputPanel = new JPanel();
              inputPanel.setLayout(new GridLayout(5,2));
              inputPanel.add(new Label("Inventory Number"));
              final JTextField numberField = new JTextField(15);
              inputPanel.add(numberField);
              inputPanel.add(new Label("Name"));
              final JTextField nameField = new JTextField(15);
              inputPanel.add(nameField);
              gui.add(inputPanel, BorderLayout.NORTH);
              final DefaultListModel dfl = new DefaultListModel();
              JList jl = new JList(dfl);
              JScrollPane jsp = new JScrollPane(jl);
              gui.add(jsp);
              JPanel southPanel = new JPanel();
              southPanel.setLayout(new GridLayout(2,1));
              final JTextField errorMsg = new JTextField();
              errorMsg.setEditable(false);
              southPanel.add(errorMsg);
              JPanel buttonPanel = new JPanel();
              southPanel.add(buttonPanel);
              JButton addButton = new JButton("Add");
              addButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        String number = numberField.getText();
                          numberField.setText("");
                         String name = nameField.getText();
                          nameField.setText("");
                               hash.put(number, name);
                               count++;
              buttonPanel.add(addButton);
              JButton deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(deleteButton);
              JButton findButton = new JButton("Find");
              findButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                        String temp = hashMap.get(number);
                              dfl.addElement(temp);
              buttonPanel.add(findButton);
              JButton showButton = new JButton("Show");
              showButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                          for (Item p : item) {
                              dfl.addElement(p);
              buttonPanel.add(showButton);
              JButton saveButton = new JButton("Save");
              saveButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(saveButton);
              JButton restoreButton = new JButton("Restore");
              restoreButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(restoreButton);
              JButton exitButton = new JButton("Exit");
              exitButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(1);
              buttonPanel.add(exitButton);
              gui.add(southPanel, BorderLayout.SOUTH);
              gui.pack();
              gui.setVisible(true);
    }I know a lot of those buttons are missing functions, but I want to get clear on how to implement a HashMap here. Any help or insight will be greatly appreciated.

    Hey thanks for that, it was some nice insight. However I'm still stumped on how HashMap needs to work in this situation. It worked fine with an object array, but this is stumping me good. To be a little more specific, I need several functions to happen with this HashMap, each correlating with a button for the GUI.
    It needs to be able to add Item objects to the HashMap (the key is the inventory number, and the value is the Item object), it needs to be able to delete an Item object (by using the inventory number), it needs to be able to find Items by inventory number, show all Items currently in the HashMap, save the info in the HashMap to a file on disk by using ObjectStreams, and a restore button just loads the data from that file to the HashMap.
    It's a lot right? :D
    I'm struggling to get anything to work with a HashMap however. If I could get some assistance with any of these functions, I would greatly appreciate it. Here's my updated code:
    import java.util.HashMap;
    import java.util.Iterator;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.Label;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultListModel;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.JScrollPane;
    public class InventoryGUI {
         //private static Item[] item = new Item[10];
         HashMap hash = new HashMap();
         private static int count = 0;
         public static void main(String[] args) {
              JFrame gui = new JFrame("Project 2 GUI");
              gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              JPanel inputPanel = new JPanel();
              inputPanel.setLayout(new GridLayout(5,2));
              inputPanel.add(new Label("Inventory Number"));
              final JTextField numberField = new JTextField(15);
              inputPanel.add(numberField);
              inputPanel.add(new Label("Name"));
              final JTextField nameField = new JTextField(15);
              inputPanel.add(nameField);
              inputPanel.add(new Label("Manufacturer"));
              final JTextField manField = new JTextField(15);
              inputPanel.add(manField);
              inputPanel.add(new Label("Description"));
              final JTextField descField = new JTextField(15);
              inputPanel.add(descField);
              inputPanel.add(new Label("Price"));
              final JTextField priceField = new JTextField(15);
              inputPanel.add(priceField);
              gui.add(inputPanel, BorderLayout.NORTH);
              final DefaultListModel dfl = new DefaultListModel();
              JList jl = new JList(dfl);
              JScrollPane jsp = new JScrollPane(jl);
              gui.add(jsp);
              JPanel southPanel = new JPanel();
              southPanel.setLayout(new GridLayout(2,1));
              final JTextField errorMsg = new JTextField();
              errorMsg.setEditable(false);
              southPanel.add(errorMsg);
              JPanel buttonPanel = new JPanel();
              southPanel.add(buttonPanel);
              JButton addButton = new JButton("Add");
              addButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        String number = numberField.getText();
                          numberField.setText("");
                         String name = nameField.getText();
                          nameField.setText("");
                         String manufacturer = manField.getText();
                          manField.setText("");
                         String description = descField.getText();
                          descField.setText("");
                         float price = Integer.parseInt(priceField.getText());
                          priceField.setText("");
                             Item myItem=new Item(number, name, manufacturer, description, price);
                               hash.put(number, myItem);
                               count++;
              buttonPanel.add(addButton);
              JButton deleteButton = new JButton("Delete");
              deleteButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                   dfl.clear();
                   String number = numberField.getText();
                    numberField.setText("");
                   hashMap.remove(number);
              buttonPanel.add(deleteButton);
              JButton findButton = new JButton("Find");
              findButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                        String number = numberField.getText();
                           numberField.setText("");
                        Item temp = new Item(hashMap.get(number));
                              dfl.addElement(temp);
              buttonPanel.add(findButton);
              JButton showButton = new JButton("Show");
              showButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
                        dfl.clear();
                          for (Item p : item) {
                              dfl.addElement(p);
              buttonPanel.add(showButton);
              JButton saveButton = new JButton("Save");
              saveButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(saveButton);
              JButton restoreButton = new JButton("Restore");
              restoreButton.addActionListener(new ActionListener() {
                  public void actionPerformed(ActionEvent ae) {
              buttonPanel.add(restoreButton);
              JButton exitButton = new JButton("Exit");
              exitButton.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        System.exit(1);
              buttonPanel.add(exitButton);
              gui.add(southPanel, BorderLayout.SOUTH);
              gui.pack();
              gui.setVisible(true);
    }Thanks for any help you can give me!

  • Map (Hashmap) to Array

    Hello Java Friends,
    Please, I have a map (Mappings = new HashMap<String, Integer>) which contains both String and Integer elements. I wanted to store the string elements of the Map in a String Array and Integer elements in Integer Array but end up with error messages. How can I implement it?
    See part of my code below:
    public class Tryit{
    private  Map<String, Integer> Mappings;
    String[]StringElem;
    int [] IntegerElem;
    public Tryit(){
    Mappings  = new HashMap<String, Integer>()
    StringElem = new String [100];
    IntegerElem = new int [100];
    for (String index : Mappings.KeySet()){
    StringElem = index;
    for (int i : Mappings.values(){
    IntegerElem = i;
    }

    Hello friends,
    The idea you gave me worked but still I am having a small problem: I have two classes, class A and B. In Class A, I implemented a set and get method which I will use in Class B to retrieve the keys and Values. But when I call the get method in Class B, I always get null. The arrays in both classes are all declared globally.
    Get and Set Method in Class A :
    public void setKeyValues() {
              int i = 0;
              for(Map.Entry<String, Integer> e: map.entrySet()) {
                   ElementName= e.getKey();
              i++;
    public String []getKeyValues(){
         return ElementName;
    Call the Get Method in Class B
    import package X.A
    public class B{
    private String [] names;
    public B(){
    A bix = new A();
    int length = bix.getKeyValues().length;
    names = new String[length];
    System.out.printf ("%d", gettingKeys(bix.getKeyValues());
    public String[] gettingKeys(String []naming) {
              names = new int[bix.getKeyValues().length];
              int size = naming.length;
              for (int p = 0; p < size; p++) {
                   names[p]=naming[p];
                   p++;
              return names;
         }Please where is the problem ?? I am unable to read and print the map values and keys from another friend class.
    Jona_T

Maybe you are looking for

  • Can you connect iPhone and iPad to iTunes at same time?

    Just received my new iPad2 and it will not show up in iTunes. I have my iPhone connected for a long time, but even if I disconnect it the iPad does not show up. Any Ideas?

  • Errors while transaction download from ECC- CRM

    we are trying to download transactions from ECC 5.0 to CRM 5.0. the initial download has stopped in between and we get an error "SysFail" in the Inbound queue (SMQ2). Information on this error is "The current application triggered a termination with

  • ACR 4.1 defaults to 8 bit

    Using Photoshop CS3 under Windows XP... Just spotted that when I open a RAW (Canon) file with CS3 (and Camera RAW 4.1), it defaults to 8-bit workflow settings (and I have to change the bit depth via the drop down box). CS2 defaulted to 16-bit At the

  • How to create custom workflow for document library?

    Hi All, I have a document library with a custom  people picker column "assign to". Need to create approval workflow using designer, approval must send to person who is selected in "assign to" column. I tried with designer workflow,But finally facing

  • Regarding address to print in smartform

    Hi, i have requirement, when im printing a smartform of purchase order,its displaying 'delivery to(plant address)' is printing but my requirement is when i select check box of subcontractor at item level it should display that subcontractor address a