Using Hashtable

Hello,
I need to store <key, value> pairs in a hashtable so that I can retrieve it at a later point in time. However, the key is an object of my user defined class. The problem I'm facing is that I can put the <key, value> pair in Hashtable but at a later point in time, I'm not able to retrieve value for a given key and I get a null value always. Is this problem happening because in my user defined class I haven't implemented "equals" method? Or is it happening due to some other reason. I've given below the code snippet of my program.
class C {
int val ;
public C(int v) {
this.val = v ;
class Test {
public static void main(String args[]) {
Hashtable t = new Hashtable() ;
t.put(new C(10), new Integer(5)) ;
/* And here, I get a null object, where as I should get the integer object that
was put in the hashtable. */
Integer i = (Integer)t.get(new C(10)) ;
Thank you,
Venkatesh

Hi,
The problem lies in your put and get.
t.put(new C(10), new Integer(5)) ;By passing the hashtable key parameter as new C(10), i assume that the JVM is getting a memory allocation/reference.
t.get(new C(10)) ;Same over here, you are creating another new reference (new instance) different from the put, therefore it return u a null.
Cheers hope it help.
; )

Similar Messages

  • When should I use HashTable and how to use it.

    I have created a set of diamond and retangular images with different colors and one color is assigned to one objective type.
    My application reads the XML file to get information about these objective type to populate it into the GUI with its
    associated attributes such as time, distance, longtitude latitude etc.. How do I store and retrieve these information.
    I think of using hashtable but not sure. Could you please help some idea .
    Thanks

    use ur code like this to maintain multivalues
    ArrayList al=new ArrayList();
    al.add(new Bean(value1,value2,value3));
    HashTable ht=new HashTable();
    ht.add(key,al);

  • Need help in using hashtable as a property of a form bean

    Hi,
    Is it possible to use a hashtable as a property of the bean.
    Well this is the problem i have
    I am using a hashtable as property and i want it to store from(/retrive into} form as ints/strings
    I have a
    JSP Page
    SampleAction --Action
    SampleForm --ActionForm
    Sample(bean)
    =============
    JSP Page
    (within the html:form tag)
    <html:text property="sample.number" />
    ====================
    struts-config links to
    SampleAction
    SampleForm
    ==============
    SampleForm
    Sample sample = new Sample();
    reset(){ ...impl...}
    validate(){.... impl.....}
    =================
    Sample.java
    private Hashtable prop = new Hashtable();
    public int getNumber()
       return ((Integer)prop.get("number")).intValue();
    public void setNumber(int number)
       prop.put("number",new Integer(number));
    ====================================
    this setup understandbly gives me a error like this
    no getter method for property sample.number
    PLEASE DO remember that i have a large number of mixed types in my form that needs to be populated into the bean and i detest using that many variables(in the bean)
    I NEED TO A KNOW A SOLN. PLEASE
    Thanx in advance
    cheers
    Ash

    Hi,
    I think the solution for your problem is
    put a form tag in your jsp page.
    name it as your form name defined in the struts-config.xml.
    in your case
    it is 'sample'.
    And make changes in the html:text tag like,
    <html:text name="sample" property="number" />
    Hope it will work.. have fun !!!

  • How to use Hashtable in Rules Engine. And objects within objects in rules

    This is something to do with the JBoss Rules Engine.
    I have an object called 'Employee' containing variables name(string), age(int), sex(string), an object Skill and other fields not relevant.
    Now the Skill object contains name and desc as variables.
    And now i have another seperate object called Test containing two hashtable: inputHT and outputHT.
    i have appropriate data in each of the objects and the hashtable:
    Employee e = new Employee();
    e.setName("Name");
    e.setAge(18);
    e.setSex("f");
    e.getSkill().setSkill("Trainer");
    Hashtable ht = new Hashtable();
    ht.put("age", new Integer(e.getAge());
    ht.put("sex", e.getSex());
    Test t = new Test();
    t.setInputHT(ht);
    Since this is something to do with drools rules: I have the appropriate code even for that.
    Like obtaining the rules defined(.drl files) in a stream, constructing the package builder, rulebase and the working memory.
    I will now explain u my .drl files(ie the rules that i have defined) and the error that i am encountering
    when I have the rule as the following there is no error:
    rule "testRule1"
    when
    e:Employee(age >= 18, sex == "f")
    then
    System.out.println("The lady can marry");
    end
    In the above rule we can see that only two simple variables contained in the employee object is being accessed and there is no error encountered.
    But when I try to access the object "skill" in the employee object, the rule throws me an error when i am constructing the packageBuilder:
    rule "testRule2"
    when
    e:Employee(skill.name == "Trainer")
    then
    System.out.println("The skill is trainer");
    end
    The error thrown is : unexpected token 'skill' and many other dump errors and also error: expected token ')'
    I tried changing the when clause as the following:
    when
    e:Employee(skill.getName() == "Trainer")
    and also
    when
    e:Employee(skill.getName().equals("Trainer"))
    All of them throws the same above error.
    But at the same time if i access only object without its variables, it is working fine. Like:
    rule "testRule2"
    when
    e:Employee(skill == "Trainer")
    then
    System.out.println("The skill is trainer");
    end
    The above rule works properly and does not throw any error. But it is not a valid rule. But syntactically it is correct. and does not throw any error during packageBuilder.
    Similarly, the problem is with the Hashtable
    The below code works fine, but rulewise it is not valid, but syntactically correct. and does not throw any error
    rule "testHT1"
    when
    t:Test(inputHT == "f")
    then
    System.out.println("Print this");
    end
    But the following code throws error, telling unexpected token 'inputHT' :
    rule "testHT1"
    when
    t:Test(inputHT.get("sex") == "f")
    then
    System.out.println("Lady");
    end
    I even changed the when clause, but did not get the appropriate result and it threw me error.
    when
    t:Test(((String)input.get("sex")) == "f")
    and also many other variants but of no use.
    It would be of great help if u or anyone else could reply to this with some solution
    Thank you in advance

    http://forum.java.sun.com/thread.jspa?threadID=774018

  • How to use hashtable values

    if i get all lovsession results in to a hash table
    how to use them
    i mean how to use the value of particular field in hash table(lov ).

    I'm not clear what exactly are you looking for? Is it just the printing/reading of values in hashtable or some interaction of those values with beans?
    --Shiv                                                                                                                                                                                                                                                                                                                               

  • Fill combobox from CSV using hashtable

    Hi, i created a simple windows form with a combobox that i im trying to fill with the full name column in my csv and i want it to return the  abreviated name column value in a variable so i used a hashtable and added both columns, but after selecting
    an item from the combobox, the $namehash[$return] is null. Shouldnt it return the abreviated name?
    My csv is comma seperated
    Name, Shortname
    Michigan,MI
    Ohio,OH
    Import-Module Activedirectory
    function button ($WF) {
    ###################Load Assembly for creating form & button######
    [void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
    [void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)
    #####Define the form size & placement
    $form = New-Object “System.Windows.Forms.Form”;
    $form.Width = 500;
    $form.Height = 190;
    $form.Text = $title;
    $form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
    $form.ControlBox = $True
    ##############Define text label2
    $textLabel2 = New-Object “System.Windows.Forms.Label”;
    $textLabel2.Left = 25;
    $textLabel2.Top = 80;
    $textLabel2.Text = $WF;
    ############Define text box2 for input
    $cBox2 = New-Object “System.Windows.Forms.combobox”;
    $cBox2.Left = 150;
    $cBox2.Top = 80;
    $cBox2.width = 200;
    ###############"Add descriptions to combo box"##############
    $NameHash = @{}
    import-csv 'C:\temp\test_cidb.csv' | ForEach-Object {
    $cBox2.Items.Add($_.Description)
    $NameHash.Add($_.Name,$_.Shortname)
    ############Define text box3 for input
    #############Define default values for the input boxes
    $defaultValue = “”
    $cBox2.Text = $defaultValue;
    #############define OK button
    $button = New-Object “System.Windows.Forms.Button”;
    $button.Left = 360;
    $button.Top = 45;
    $button.Width = 100;
    $button.Text = “Ok”;
    $Button.Cursor = [System.Windows.Forms.Cursors]::Hand
    $Button.Font = New-Object System.Drawing.Font("Times New Roman",12,[System.Drawing.FontStyle]::BOLD)
    ############# This is when you have to close the form after getting values
    $eventHandler = [System.EventHandler]{
    $cBox2.Text;
    $form.Close();};
    $button.Add_Click($eventHandler) ;
    #############Add controls to all the above objects defined
    $form.Controls.Add($button);
    $form.Controls.Add($textLabel2);
    $form.Controls.Add($cBox2);
    $ret = $form.ShowDialog();
    #################return values
    return $cbox2.text
    $return= button “Job Descriptions"

    I solved my own issue by creating a datatable using that as the data source and binded the combobox using displaymember, valuemember, datasource classes. Exactly what I was wanting do do.
    $reader = new-object System.IO.StreamReader($csvfile)
    $line = $reader.ReadLine()
    $columns = $line.Split($csvdelimiter)
    foreach ($column in $columns) {$null = $datatable.Columns.Add($column) }
    while (($line = $reader.ReadLine()) -ne $null) {
    $row = $datatable.NewRow()
    $row.itemarray = $line.Split($csvdelimiter)
    $datatable.Rows.Add($row)
    $cbox2.DisplayMember = "Name"
    $cbox2.ValueMember = "Shortname"
    $cbox2.DataSource = $datatable
    $States=cbox2.SelectedValue

  • Reposting:urgent....how to use hashtable values

    Hi
    if i get all lovsession results in to a hash table
    how to use them
    i mean how to use the value of particular field in hash table(lov ).
    is it <hashtable>.get(object name);
    if it is what should be my object name...is it VO attribute of LOV???or the Id in that lov page??
    please help me out..
    Regards
    Sandeep.G

    if(pageContext.isLovEvent())
    String lovInputSourceId = pageContext.getParameter(SOURCE_PARAM);
    Hashtable lovResults = pageContext.getLovResultsFromSession(lovInputSourceId);
    if (lovResults != null)
    value = (String) lovResults.get("<Lov Item Name>");
    }

  • Help on using hashtables with sub structures inside

    Hi everyone,
    I'm currently working on a script that scans Active Directory for computers, and lists current users logged, and logs to an hashtable the username as key, and a count as a value.
    After that it sends an email with the list. This part is all developed and working. Now I want to go further, and in the hash table, I would like to have as the key the username, and as the value the counter and a list of the computer names where the user
    is logged on.
    I have this code for working with the hashtable:
    ForEach ($c in $computer) {
    #Get explorer.exe processes
    $proc = gwmi win32_process -computer $c -Filter "Name = 'explorer.exe'"
    #Go through collection of processes
    ForEach ($p in $proc) {
    $temp = "" | Select Computer, Domain, User
    $temp.computer = $c
    $temp.user = ($p.GetOwner()).User
    $temp.domain = ($p.GetOwner()).Domain
    $report += $temp
    If($UsersList.ContainsKey($temp.user) -eq 1){
    $UsersList[$temp.user] = $UsersList[$temp.user] + 1
    #$UsersList
    Else {
    $UsersList.add($temp.user,1)
    Can I have it the way I'd like, or have to change my approach?
    Thanks in advance
    Nuno Silva

    Thanks for the help. One more question regarding printing the arraylist.
    I use the code below to print everything. I can print successfully the key and value but get an error on the computerlist.
    ($UsersList.GetEnumerator() |
    Sort-Object Value -descending |
    % { "{0}, {1} - {3}" -f $_.key, $_.value.Count, $_.value.ComputerList })
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
    +     % { "{0}, {1} - {3}" -f $_.key, $_.value.Count, $_.value.ComputerList[0] })
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: ({0}, {1} - {3}:String) [], RuntimeException
        + FullyQualifiedErrorId : FormatError
    Error formatting a string: Index (zero based) must be greater than or equal to zero and less than the size of the argument list..
    How can I print it out?
    Thanks in advance,
    Nuno Silva

  • Help with program using hashtable to count words & other chars in txt file

    I need to use only a hashtable to count the occurences words and chars in a text file and display them alphabetically. I am not to use anything but the hashtable. so far, I can get it to count only the words in the file and not the chars, I want to know how to make it count the chars (,.;:?(){}[]!@#$%^&\t\"<>/`~ ) that may be found and if it is possible to get it to display them in a sorted (alphabetical) order w/o using anything else.
    This is what I have: mport java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane;
    class words{
    String word;
    int count;
    public class WordCount{
    static Hashtable h=new Hashtable();
    static words w;
    static void countWords(String s){
    if((w=(words)h.get((java.lang.Object)s))==null){
    w=new words();
    w.word=s;
    w.count=1;
    h.put(s,w);
    }else{
    w.count++;
    h.remove(s);
    h.put(s,w);
    public static void main(String args[]){
    String s;
    StringTokenizer st;
    String t;
    String fn = JOptionPane.showInputDialog("Enter the filename:");
    BufferedReader br = null;
    try{
    br = new BufferedReader(new FileReader(fn));
    s=br.readLine();
    while(s!=null){
    st= new StringTokenizer(s, " ,.;:?(){}[]!@#$%^&\t\"<>/`~  ");
    // Split your words.
    while(st.hasMoreTokens()){
    t=st.nextToken();
    countWords(t);
    s=br.readLine();
    }catch(Exception e){
    e.printStackTrace();
    Enumeration e=h.elements();
    w=(words)e.nextElement();
    while(e.hasMoreElements()){
    System.out.println(w.word + " " + w.count);
    w=(words)e.nextElement();
    System.exit(0);
    }

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • NEED HELP WITH WORD & CHAR COUNT USING HASHTABLE

    I have to use a hashtable to be able to count all the words and characters (#'s, punctuations, etc) from a file
    I have been able to get it to correctly count the words in the file but none of the characters and it also does not display the words alphabetically and just displays it in an odd way
    Here's the code: public static void main (String [] args)
          Hashtable table = new Hashtable();
          String input = JOptionPane.showInputDialog("Enter the filename:");
          try{
          BufferedReader br = new BufferedReader(new FileReader(input));
          String s = br.readLine();
          StringTokenizer words = new StringTokenizer( s, " \n\t\r" );
            while ( words.hasMoreTokens() ) {
             String word = words.nextToken().toLowerCase(); // get word
             // if the table contains the word
             if ( table.containsKey( word ) ) {
                Integer count = (Integer) table.get( word ); // get value
                // and increment it
                table.put( word, new Integer( count.intValue() + 1 ) );
             else // otherwise add the word with a value of 1
                table.put( word, new Integer( 1 ) );
           } // end while
             String output = "";
          Enumeration keys = table.keys();
          // iterate through the keys
          while ( keys.hasMoreElements() ) {
             Object currentKey = keys.nextElement();
             output += currentKey + "\t" + table.get( currentKey ) + "\n";
             System.out.println(output.toString());
          catch (IOException e)
            System.out.println(e);
          }The output that I get for a file containing the line " Hi this is my java program" is:
    this     1
    this     1
    program     1
    this     1
    program     1
    hi     1
    this     1
    program     1
    hi     1
    java     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    this     1
    program     1
    hi     1
    java     1
    is     1
    my     1
    I'm not sure what I am doing wrong and help would be greatly appreciated.

    I have been able to get it to correctly count the
    words in the file but none of the characters and it
    also does not display the words alphabetically and
    just displays it in an odd way
    That's because hash tables are not ordered; to maintain order of insertion you could use LinkedHashMap and to maintain alphabetical order TreeMap.

  • AbstractTableModel using HashTable

    Hi,
    I'm trying to build an AbstractTableModel, and I want to store my data in a HashTable - but I've never used either.
    Do you have a good example for me to look over? Especially which functions should I override in the model, and how do I fill the HashTable, before creating the table.
    Sorry if this has been forumed before, couldn't quite find something that helps me...

    Sorry for the double.
    Regarding the HashTable i also have questions:
    1) how do i make a custom hash key generator, i would like to define each key by two parameters
    2) to optimize the hashtable: do you know of a good algorithm for creating the key function, with two parameters, when most of the input will consist of both parameters in close proximity. for example (1,1) (1,2) (2,1) (2,3) (4,4) (5,4).....
    Thanks,
    Eran

  • Replacin characters in a string using hashtable

    hello
    i have hashtable on java with many keys and their values
    i want to read a string and search in it if it contains one or more of the keys and replace them by their values
    n.b. i tried to make replace of each key alone but i have many keys it will be very long
    how can i make a replace method for all the keys togother
    thank you

    You can greatly simplify things if you can separate potential matched strings out of you source before looking them up, often in these cases the a regular expression pattern matcher will do nicely. For example if the source if divided into words and each entry in the map is a single word, or if there some kind of escape convention like ${keyword}.
    If not, then much depends on the relative size of the map and the source string. For a small map it probably easiest just to search and replace in the whole string for each key in turn.
    An approach that might work if the number of keys to be replaced is large is to read the source character by character and keep a list of keys that you might just have read the first n letters of.

  • Using Hashtable Class

    Hi, I try to insert two different objects into a hashtable. I want the second
    one to replace the first one. I override the equals() and hashCode() methods
    explicitly so that they are equal and have the same hashcodes.
    But it doesn't work. Anybody can help me how I can do it ?
    Thanks a lot.
    Lisa
    import java.util.*;
    class Test {
    public static void main (String[] argv){
    Book b1 = new Book("aaa");
    Book b2 = new Book("bbb");
    Hashtable hs = new Hashtable(10);
    hs.put((Book)b1, "1");
    System.out.println(hs.size());
    hs.put((Book)b2, "2");
    System.out.println(hs.size());
    public class Book {
    public String name;
    public Book(String name){
    this.name = name;
    public int hashCode(){
    return 3;
    public boolean equals(Book b){
    return true;

    Hello,
    public boolean equals(Object b)and not
    public boolean equals(Book b)One must override the function.
    I hope it helps.

  • Use of Hashtable in a JSP

    I have a JSP page, displaying Employee details(5 attrbutes in total)
    (code, name, address, telephone, email)
    And this employee is coming from Employee table, which is having around 50 attributes, and I have one entity class for the employee doing the database operation.
    Now since I have to show only 5 fields, using Employee class (which is having 50 attributes) will be very heavy.
    Should I create a new bean class EmployeeView having only 5 attributes or shall i go for <b>hashtable</b> , having 5 entries, with attribute name as key and attribute value as key value.
    Are there any disadvantage on using hashtable like this, or what can be better approach.
    Please suggest.

    Hi,
    The best way for this is to create view for the table in the database.
    Then you can access the view like how you access a table.
    This will reduce the amount of data transfer from database to your application.
    Hope this helps.
    Good Luck.
    Gayam.Srinivasa Reddy
    Developer Technical Support
    Sun Micro Sysytems
    http://www.sun.com/developers/support/

  • Alternative to Hashtable? Got lots of data and "OutOfMemoryError"

    Hello,
    I am working on an application (CLDC1.1 and MIDP2.0, using NetBeans) and have to use a large look-up table with about 50 000 entries. During runtime the application is set to look up entries xxx times from the table, as fast as possible of course. I have used Hashtable for the table data (keys/value) until now, and distributed it all over several files / classes (singleton, static init) with a Hashtable for each class. Have not yet completely inserted the look-up table (about 30% percent left, and .jar size is 300 KB), but now I get the following error: Uncaught exception java/lang/OutOfMemoryError. All hashtables are initialized with a final size.
    I should have ca. 2 MB of RAM with the emulator Im using . Printing out freeMemory() from the Runtime I notice that the free mem number decreases fast, towards zero, and then it starts over again - decreasing from somewhere under 2 000 000 bytes down to 0. Not a wiz with debugging, but I guess I have to dive deeper into my garbage collection :)
    Is there a better way to store the keys (int) and values (int) of the look-up table? Like an associative array (pseudo): [["key"]=>[value]]
    Should I check out RMS (slow?), or some sorts of file handling? Or maybe a combination of Hashtables in memory and also RMS..?
    If someone could help with a hint or two, I would be very very thankful!
    Tib

    50 000 * (4 + 4) B = 400kB of uncompressed data. That's quite a lot for a MIDlet, but it's probably ok if the rest of your application is not so large. Hashtables need more than the size of the data to be effective, so I think an array of key-value pairs (sorted on the keys) would be best here, and of course using binary search when looking up the values.
    Or you can look at the range, distribution etc. of the keys, perhaps they will allow some optimization.

Maybe you are looking for

  • Almost every program not from Apple crashes at startup, every time

    Hi! I have a Macbook, with a fresh OS X 10.6.6 installation (about 1 month old). I have installed MS Office, Firefox, Chrome and Skype as 3rd Party programs. Suddenly, I don't know why this happens, most of the programs don't run anymore. If I try to

  • Screen does not turn off near my ear

    The screen backlight does not turn off when you place it near your ear. Anyone else have this problem?

  • BAPI FM with Submit Statement

    Hi, I want to use BAPI Function Module and Submit Statement in a program. How i can use this, Please help me since this is very urgent. Regards Krishna

  • RFC   R3- XI

    Hi i've defined a receiver step in my BPM in order to receive a RFC that contains some info. The problem is that i don't know how to define the components in repository and directory (abstract, async, receiver determination, communication channel ...

  • Exporting with colors used in initial preview

    Hi, I often notice that the fast initial preview has a desirable set of colors, however when it renders high-quality preview, the colors become desaturated. My question is -- how can I export the photograph using the set of colors used in initial pre