Java's Hashtable, HashMap and properties

Source: Internet
Author: User
Tags rehash

Hashtable inherits from the older dictionary, and HashMap is the implementation of the interface map.

HashMap is a lightweight implementation of Hashtable, HashMap is not thread-safe, and Hashtable is thread-safe.

HashMap allows key or value to be null, and Hashtable is not allowed.

In terms of efficiency: the efficiency of hashmap is slightly too hashtable.

Properties is a subclass of Hashtable, but properties adds two methods, and load () and store () can either import directly or write the mappings to a file. In addition, the properties is a mapping of <String,String>.

1, Hashtable and hashmap the same place

Java contains two classes, java.util.Hashtable and JAVA.UTIL.HASHMAP, which provide a multi-purpose Hashtable mechanism. The Hashtable and HashMap objects allow you to combine a key with a value and enter this pair of key/value into the table using the put () method. Then you can get this value (value) by calling the Get () method and using the key as a parameter. As long as two basic requirements are met,key and value can be any object . Note that because key and value must be objects , the original type (primitive types) must be converted to an object by using a method such as Integer (int). Here's a simple example code:

1. First create a Hashtable, save 1, 2, 33 objects.

Hashtable numbers = new Hashtable ();

Numbers.put ("One", New Integer (1));

Numbers.put ("n", New Integer (2));

Numbers.put ("Three", New Integer (3));

2. Find

Integer n = (integer) numbers.get ("a");

if (n! = null) {

System.out.println ("both =" + N);

}

In order to use an object of a particular class as a key, this class must provide two methods, Equals () and Hashcode (). these two methods are in Java.lang.Object, so all classes can inherit both methods, but the implementations of the two methods in the object class are generally useless, so you usually need to overload both methods yourself.

The Equals () method compares its object to another object and returns True if the two objects represent the same information. The method also looks at and ensures that the two objects belong to the same class. If two reference objects are exactly the same object, Object.Equals () returns True, which explains why this method is often not a good fit. In most cases, you need a way to compare a field to a field, so we think the different objects representing the same data are equal.

The Hashcode () method generates an int value by executing a hash function using the contents of the object. Hashtable and HashMap Use this value to figure out which bucket (Hashion) (or list) a pair of Key/value is located in.

If you want to create a Hashtable, this hashtable uses your own defined class object as key, then you should be sure that the Equals () and Hashcode () methods of this class provide useful values. Start by looking at your extended class to determine if its implementation meets your needs. If not, you should reload the method.

The basic design constraint of any Equals () method is that it should return true if the object passed to it belongs to the same class and its data field is set to a value that represents the same data. You should also be sure that if you pass an empty argument to the method, then your code returns false:public Boolean equals (Object O)

{

if ((o = = null)

|| ! (o instanceof MyClass))

{

return false;

}

}

In addition, some rules should be kept in mind when designing a Hashcode () method. First, the method must return the same value for a particular object, regardless of how many times the method was called (of course, as long as the object's content does not change between calls, this should be avoided when an object is used as a Hashtable key). Second, if the two objects defined by your equals () method are equal, they must also generate the same hash code. Thirdly, this is more like a guideline than a principle, you should try to design a method that produces different results for different object content. This does not matter if occasionally different objects produce the same hash code exactly. However, if the method can only return values ranging from 1 to 10, then only 10 lists can be used, regardless of the number of lists in Hashtable.

String class has been implemented as required hashcode () , because when you design your own keyword class, you can call String.hash () , but StringBuffer () cannot be used as a keyword class, it does not implement hashcode () as required.

2, Hashtable and HashMap different places:

There are three important differences between the Hashtable and the HashMap class. The first difference is mainly historical reasons. Hashtable is based on the old dictionary class ,HashMap is an implementation of the map interface introduced by Java 1.2 .

Perhaps the most important difference is that the Hashtable method is synchronous , and the HashMap method is not . This means that while you can use a hashtable in a multithreaded application without taking any special action, you have to provide an external synchronization for a hashmap as well. a convenient way is to use the static Synchronizedmap () method of the collections class, which creates a thread-safe map object and returns it as a encapsulated object . The method of this object allows you to synchronize access to potential hashmap. The result is that when you don't need to sync, you can't cut off synchronization in Hashtable (like in a single-threaded application), and synchronization adds a lot of processing overhead.

The 3rd difference is that only HashMap can let you use NULL as a key or valuefor the entry of a table. HashMap only one record can be an empty key , but any number of entries can be empty value. This means that if a search key is not found in the table, or if a search key is found, but it is an empty value, then get () returns NULL. If necessary, use the Containkey () method to differentiate between the two cases.

Some data suggest, when need to synchronize, use Hashtable, converse with HashMap. However, because HashMap can be synchronized when needed, HashMap functions more than Hashtable, and it is not based on a stale class, it is argued that hashmap in all cases takes precedence over Hashtable.

3.Hashtable Performance

The main factor affecting Hashtable efficacy is the average length of the list in the table, because the average search time is directly related to the average length. Obviously, to reduce the average length, you have to increase the number of lists in Hashtable, and if the number of lists is so large that most lists or all lists contain only one record, you get the best search efficiency. However, it may be too much to do. If you have a lot more lists of hashtable than data entries, you don't have to spend that kind of memory, and in some cases it's impossible to accept that.

In our previous example, we know in advance how many records we have in 1,000. Knowing this, we can decide how many lists our hashtable should contain to achieve the best compromise between search speed and memory usage efficiency. However, in many cases you do not know in advance how many records you are dealing with, the file that the data is being read from may be expanding, or the number of records may change greatly day by day.

As entries increase, the Hashtable and HashMap classes handle this problem by dynamically extending the table. These two classes have constructors that accept the initial number of lists in the table, and a load factor as a parameter (load factor):

Public Hashtable (int initialcapacity,float loadfactor)

Public HashMap (int initialcapacity,float loadfactor)

Multiply these two numbers to calculate a critical value. Each time a new entry is added to the Hashtable, the count is updated, and when the count exceeds the threshold, the table is reset (rehash). (The number of lists increases to twice times the previous number plus 1, and all entries are transferred to the correct list.) The default constructor setting initially has a capacity of 11 and the load factor is 0.75, so the threshold value is 8. When the Nineth record is added to the table, the hash table is resized to have 23 lists, and the new threshold value will be 17 (the integer portion of the 23*0.75). As you can see, the load factor is the upper limit of the number of average lists in the hash table, which means that, by default, there are very few lists with more than one record in the Hashtable. To compare our original example, in that case we have 1,000 records, distributed in 10 lists. If we use the default value, this table will be extended to contain more than 1,500 lists. But you can control this. If the number of lists multiplied by the load factor is greater than the number of entries you are working with, then the table will never be re-made, so we can follow the example below://table will not rehash until it

has 1,100 entries (10*110):

Hashtable myhashtable = new Hashtable (110.0F);

You might not want to do this unless you don't save memory for the empty list, and you don't mind the extra search time, which can happen in embedded systems. However, this approach can be useful because the reset takes a lot of computing time, and this approach guarantees that it will never happen again.

Note that although the call to put () causes the table to grow (the number of lists increases), calling remove () does not have the opposite result. So, if you have a large table and delete most of the entries from it, you will have a large but mostly empty table.

Hashtable test :

//mykey.java
Class MyKey {
 private String name = null;
 private int = 0; 
 
 public MyKey (String name, int age)
 {
   This.name=name;
  this.age=age;
 }
 public boolean equals (Object obj) {
  //Todo:add your code here
  if (obj instanceof MyKey)
  {
   mykey objtemp= (MyKey) obj;   // The compiler cannot automatically convert the object class to MyKey
   if (name.equals (objtemp.name))
   {
     return true;
   }
   else
   {
    return false;
   }
    
  }
  else
  {
   return false;
  }
 }


public int hashcode () {
Todo:add Your code here
Return Name.hashcode () +age;
}


Public String toString () {
Todo:add Your code here
Return name+ "," +age;
}

}


Hashtabletest.java

Import java.util.*;
public class Hashtabletest {


public static void Main (string[] args) {
Todo:add Your code here
Hashtable numbers=new Hashtable ();
Numbers.put (New MyKey ("Zhangsan"), New Integer (1));
Numbers.put (New MyKey ("Lisi"), New Integer (2));
Numbers.put (New MyKey ("Wangwu"), New Integer (3));

Enumeration E=numbers.keys ();
while (E.hasmoreelements ())
{
MyKey key= (MyKey) e.nextelement ();
System.out.print (key.tostring () + "=");
System.out.println (Numbers.get (key));

}
System.out.println (Numbers.get (New MyKey ("Zhangsan", 18));
}
}
HashMap Test:

Hsshmaptest.java

Import java.util.*;

Class Hashmaptest

{

public static void Printelements (Collection c,hashmap HM)

{

Iterator It=c.iterator ();

while (It.hasnext ())

{

Object Key1=it.next ();

System.out.println (key1+ "=" +hm.get (key1));

}

}

public static void Main (string[] args)

{

HashMap hm=new HashMap ();

Student s1=new Student (1, "zhang3");

Student s2=new Student (2, "li4");

Student s3=new Student (3, "wang5");

Student s4=new Student (1, "zhang3");

Hm.put (S1, "123");

Hm.put (S2, "456");

Hm.put (S3, "789");

Hm.put (S4, "321");

Set Keys=hm.keyset ();

System.out.println ("Key:");

Printelements (KEYS,HM);

}

}

Class Student

{

int num;

String name;

Student (int num,string name)

{

This.num=num;

This.name=name;

}

public int hashcode ()

{

return Num*name.hashcode ();

}

public boolean equals (Object O)

{

Student s= (Student) o;

return num==s.num && name.equals (s.name);

}

Public String toString ()

{

Return num+ ":" +name;

}

}

4. About Properties

Sometimes, you might want to use a hashtable to map the string of key to the string of value. The environment strings in DOS, WINDOWS, and Unix have some examples, such as the string path of key that is mapped to the string c:windows of value; C:windowssystem. Hashtables is a simple way to represent these, but Java provides another way.

The Java.util.Properties class is a subclass of Hashtable, designed for string keys and values. The use of the properties object is similar to the use of Hashtable, but the class adds two time-saving methods, which you should know.

The store () method saves the contents of a Properties object to a file in a readable form. The Load () method is exactly the opposite, used to read the file and set the Properties object to contain keys and values.

Note that because properties extends the Hashtable, you can use the put () method of the superclass to add keys and values that are not string objects. This is not advisable. In addition, if you use the store () for a Properties object that does not contain a string object, store () will fail. As an alternative to put () and get (), you should use SetProperty () and GetProperty (), which use the string parameter.

Properties Test:

Propertiestest.java

Package propertiestest;
Import java.io.*;
Import java.util.Properties;

public class Propertiestest {
public static void Main (string[] args) {
Todo:add Your code here
Properties Settings=new properties ();
Try
{
Settings.load (New FileInputStream ("Count.txt"));
}catch (Exception e)
{
E.printstacktrace ();
Settings.setproperty ("Count", string.valueof (0));
}

Settings.get ("Count");
int C=integer.parseint (Settings.getproperty ("Count")) +1;//getproperties returns a string, parseint () converts the string to an integer
System.out.println ("This is the" + C + "St");

Settings.put ("Count", new Integer (c). ToString ());
Settings.setproperty ("Count", new Integer (c). ToString ());
Try
{
Settings.store (New FileOutputStream ("Count.txt"), "program is used:");
}catch (Exception e)
{
E.printstacktrace ();
}
}
}

Java's Hashtable, HashMap and properties

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.