Hashtable vs Vector

Hi there,
I was just wondering if a Hashtable is more efficient than a Vector for holding small amounts of objects.
The fuctionality that I require allows me to use either but Id like to use the most efficient if I can find out which that would be.
Thanks,
Nick

Fiontan,
You can't compare two things that are not comparable.My bad, the Comparable interface is a Java 2 construct also. You could still code your own binary search for the Vector however, using the knowledge that it only contains Strings, which you can manually compare.
Or, if speed really isn't important, then you could use the existing contains (was this in 1.0?) or indexOf method to test if the string exists, and just go with the linear performance. In a list with 5 elements (Each equally likely), that's less than 3 comparisons on average, compared with more than 1 (hash + equals, at minimum) for a hashtable.
The hashtable is a special structure used to keep
objects that are unique and accessible through a
unique hashcode, so the access can be make in O(1).A hashtable is an implementation of both the (mathematical) map and (mathematical) set construct. A map is a function that literally maps a value from one set onto another value from another (or the same) set. If a map simply maps a value onto itself, then that map is just an identity map on a set.
This differs from a Vector, which is simply an ordered list of values. Such a list can be a backing for larger mathematical constructs (Indeed, a similar ordered list forms part of the backing for a hashtable). Since their purpose overlaps, there may well be cases where either is appropriate. In many such cases, there will be one which is 'obviously' more appropriate, but that's no reason to assume that in all cases it is either 'one or the other'.
But, if you don't have any key on your objects, and
you want to add the same object several times, and you
want to have an sequential ordered access : use a
Vector (or a similar structure) but not an HashTable.I'd change each of your 'and's to 'or's, since a hashtable will not fulfil any of those requirements - so any one of them will render a hashtable unusable. Note that in a set, an object forms its own key.
Just to throw a spanner in the works, I suddenly recall that in Java 1.0, String's hashCode method was rather inefficient - it creates a poor hash, and it doesn't store the result of the calculation (Meaning it is recalculated for each call to hashCode). If your strings are large, the Vector may match or out-perform the HashTable!
-Troy

Similar Messages

  • Hashtable or Vector to create Jtree ?Data from dtatbase.

    I want build JTree in JApplet .
    The JApplet is connecting to a database .
    As soon as data change ,JTree change.
    1.How can use hashtable or Vector to create Jtree ?
    the Hashtable's Data or Vector's Data from Database.
    2.How Japplet connect to a database and get data?

    1-How can use hashtable or Vector to create Jtree ?
    read JTree constrcutors in which u can use Vector for creating JTree like new JTree(myVector);
    and in this myVector u can store your own objects and override toString() method of that object (stored in Vector), but as my practice its not good.
    2.How Japplet connect to a database and get data?
    You have to make signed applet for connecting your applet with database , and sorry to say but ita a real pain in your -------------

  • Hashtables and Vectors

    Hi there !!!
    Today I made some stuff but still a lot more needs to be done.
    So first of all let me explain what is all about.
    I have to make a hashtable that contains a String as a key and a vector as a value associated with that String.The following classes extend Relation (this is an interface)
    Analogy,Cause and so on.
    The instances have as fields DestinationID and SourceID .
    The table sorts the instances as follows : the objects with the same SourceID are put in a vector that is mapped to that SourceID.There is a second table that does the same but for the DestinationID-s
    The tables I have implemented recursively
    Here is the code for one of them:
    public class AnnotationThread1 {
        private Vector v = new Vector();
        private Hashtable h_sourceID = new Hashtable();
        private Hashtable h_destinationID = new Hashtable();
        private Vector leaves = new Vector();
    /** Creates a new instance of AnnotationThread1 */
        public AnnotationThread1() {}
    /** Creates the hashtable (recursively) the key is the SourceID and the
    *value is a vector that contains all the nodes that have the same SourceID
        public Hashtable add(Relation r){
            String sourceID = r.getSourceID();
            Vector v = (Vector) h_sourceID.get(sourceID);
            //if the Vector is null we create a new one
             if (v == null) v = new Vector();
            //if we add the same node twice the second will be neglected
              if (!v.contains(r)){
               v.add(r);
               h_sourceID.put(sourceID,v);
          return h_sourceID;
        }Now i should also retrieve the so called leaves : here the ID -s that are not SourceID -s . (they are not parents so to say).I have done that for every single object (i chech whether the given Relation possesses a leaf or not) but still I can not come up with an idea how to retrieve all leaves and for example to have them in a vector .
    Here is the code how I check if one ID is a leaf or not:
    /** Asks if a given ID is a leaf or not(uses the add() method)
    *@param Relation r
    *@return false if the node does not have a leaf and true otherwise
        public boolean ifLeaf(Relation r){
          boolean ifleaf = false;
          String leaf = r.getDestinationID();
          if (!h_sourceID.containsKey(leaf)){ ifleaf = true; }
          return ifleaf;
        }If anyone has ideas I will be very glad.
    The same problems I have with finding the root.
    Thanks in advance...

    OPS I forgot to mention how is the table actually created.Well in the main class i have something like:
    public static void main(String args[]){
          AnnotationThread1 example = new AnnotationThread1();
          BackgroundInformation a = new BackgroundInformation(0.1f,0.3f,"a","b");
          example.add(a);
          Analogy b = new Analogy(0.2f,0.1f,"a","c");
          example.add(b);
          SupportArgument c = new SupportArgument(0.2f,0.1f,"b","d");
          example.add(c);The Strings are as mentioned the SourceID and the DestinationID.
    for example after writing
    System.out.printlnexample.add(c);I will get as an output(in NetBeans):
    a=[collate.AnnotationThread.BackgroundInformation@1f12c4e,    collate.AnnotationThread.Analogy@93dee9]}

  • HashTable and Vector

    when we will use hashTable and Vector..plz explain with example..

    well, the main difference is, that a vector is a simple set of objects, while a map (e.g. HashTable) maps values to keys.
    a simple example (not java specific as you can see) to make this transparent:
    "Adam",
    "Bert",
    "Cesar"
    would be a list, while a Map looks like this:
    "A" -> "Adam",
    "B" -> "Bert",
    "C" -> "Cesar"
    and with the key you can actually access the value, thus retrieving the object bound to "A" from the map will give you "Adam"

  • Null Value returned into Hashtable  from Vector (after 1.5 compilation )

    Sorry i posted the Question with a misleading heading into another thread .
    Hi , in the given peice of Code , date1 is a vector while date2 is a hashtable .
    I am storing the date from the vector in a hashtable .
    The code works fine for java 1.4 but Null value gets stored after compiling in 1.5.
    There is no error during compilation .
    Hashtable date2 = (Hashtable) date1.elementAt(0);
    cat.debug("date2"+date2.get("TO_CHAR(TO_DATE(TO_CHAR(RES_DT,DD-MON-YYYY)),DD-MON-YYYY)"));"TO_CHAR(TO_DATE(TO_CHAR(RES_DT,DD-MON-YYYY)),DD-MON-YYYY)") is the key , there is no error in that .
    cat.debug is log4j function used to write log to an text file.
    From searchin the net i got the i would have to typecast (not sure if am using the right technical term ) .
    protected Hashtable<Object,Object> lNVPair = new Hashtable<Object,Object>();
        protected Vector<Object> lNVKeys = new Vector<Object>();But how am i suppose to use it in the above state where with declaration i am assigning value at same time ?..
    Hashtable<Object,Object> date2 = (Hashtable<Object,Object>) date1.elementAt(0);

    Here is more details about date1 :
    Vector date1 = mDao.getDate(lcrnno,ltxntype,lbranchCd);Value of date1 is filled by calling a function which in turns queries the database .
    Details about the function are below .
    public Vector getDate(String pcrnno,String ptxntype,String br_cd)//throws SQLException
              Vector lResult=null;
              ResultSet lresult = null;
       try {
                                              Hashtable linner=new Hashtable();
                         lResult=new Vector();
              //String lstrquery declared  containing the query to be executed .
             mPstmt = mConn.prepareStatement(lstrquery);
           lresult = mPstmt.executeQuery();
         ResultSetMetaData lrsmd=null;
        lrsmd=lresult.getMetaData();
       int lcolCount=lrsmd.getColumnCount();
      cat.debug("Number of fields:"+lcolCount);
    while(lresult.next())
              linner=new Hashtable();
           for(int i=1;i<=lcolCount;i++) {
                   String lkey=lrsmd.getColumnName(i); //column name to be used as key
                   String lvalue=lresult.getObject(i).toString(); //value
                      linner.put(lkey,lvalue); //populating the hashtable
          }//end of for
                             lResult.add(linner); //adding to vector
      }//end of whileNote I have not added the part of code where query string created and parameters passed .
    Hope that should be enough details ...

  • Strange Problem with a Vector wraped inside a Hashtable

    Hi all ,
    I'm having a strange problem with a Vector wraped within a Hashtable inherited Class.
    My goal is to keep the order of the elements of the Hashtable so what I did was to extend Hashtable and wrap a Vector Inside of it.
    Here is what it looks like :
    package somepackage.util;
    import java.util.Enumeration;
    import java.util.Hashtable;
    import java.util.Vector;
    public class OrderedHashTable extends Hashtable {
        private Vector index;
        /** Creates a new instance of OrderedHashTable */
        public OrderedHashTable() {      
            this.index = new Vector();
    //adds a key pair value to the HashTable and adds the key at the end of the index Vector
       public synchronized Object put(Object key,Object value){      
           index.addElement(key);
           Object obj = super.put(key,value);
           System.out.println("inside OrderedHashTable Put method index size = " + index.size());
           return obj;    
    public synchronized Object remove(Object key){
           int indx = index.indexOf(key);
           index.removeElementAt(indx);
           Object obj = super.remove(key);
           return obj;
    public synchronized Enumeration getOrderedEnumeration(){
           return index.elements();
    public synchronized Object getByIndex(int indexValue){
           Object obj1 = index.elementAt(indexValue);
           Object obj2 = super.get(obj1);      
           return obj2;
       public synchronized int indexOf(Object key){
        return index.indexOf(key);
        public synchronized int getIndexSize() {
            return index.size();
        }Everything seemed to work fine util I tried to add objects using a "for" loop such as this one :
    private synchronized void testOrderedHashTable(){
            OrderedHashTable test = new OrderedHashTable();
            for (int i = 1 ; i<15; i++){
                 System.out.println("adding Object No " + i);
                 String s = new String("string number = "+i);
                 test.put(new Integer(i),s);
                 System.out.println("-----------------------------------");
            //try to list the objects
            Enumeration e = test.getOrderedEnumeration();
            while (e.hasMoreElements()){
                Integer intObj = (Integer) e.nextElement();
                System.out.println("nextObject Number = "+ intObj);
        }Here is the console output :
    Generic/JSR179: adding Object No 1
    Generic/JSR179: inside OrderedHashTable Put method index size = 1
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 2
    Generic/JSR179: inside OrderedHashTable Put method index size = 2
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 3
    Generic/JSR179: inside OrderedHashTable Put method index size = 3
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 4
    Generic/JSR179: inside OrderedHashTable Put method index size = 4
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 5
    Generic/JSR179: inside OrderedHashTable Put method index size = 5
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 6
    Generic/JSR179: inside OrderedHashTable Put method index size = 6
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 7
    Generic/JSR179: inside OrderedHashTable Put method index size = 7
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 8
    Generic/JSR179: inside OrderedHashTable Put method index size = 8
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 9
    Generic/JSR179: inside OrderedHashTable Put method index size = 10
    Generic/JSR179: inside OrderedHashTable Put method index size = 10
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 10
    Generic/JSR179: inside OrderedHashTable Put method index size = 11
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 11
    Generic/JSR179: inside OrderedHashTable Put method index size = 12
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 12
    Generic/JSR179: inside OrderedHashTable Put method index size = 13
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 13
    Generic/JSR179: inside OrderedHashTable Put method index size = 14
    Generic/JSR179: -----------------------------------
    Generic/JSR179: adding Object No 14
    Generic/JSR179: inside OrderedHashTable Put method index size = 15
    Generic/JSR179: -----------------------------------
    Generic/JSR179: nextObject Number = 1
    Generic/JSR179: nextObject Number = 2
    Generic/JSR179: nextObject Number = 3
    Generic/JSR179: nextObject Number = 4
    Generic/JSR179: nextObject Number = 5
    Generic/JSR179: nextObject Number = 6
    Generic/JSR179: nextObject Number = 7
    Generic/JSR179: nextObject Number = 8
    Generic/JSR179: nextObject Number = 9
    Generic/JSR179: nextObject Number = 9
    Generic/JSR179: nextObject Number = 10
    Generic/JSR179: nextObject Number = 11
    Generic/JSR179: nextObject Number = 12
    Generic/JSR179: nextObject Number = 13
    Generic/JSR179: nextObject Number = 14
    You can notice that the output seems correct until the insertion of object 9.
    At this point the vector size should be 9 and the output says it is 10 elements long ...
    In the final check you can notice the 9 was inserted twice ...
    I think the problem has something to do with the automatic resizing of the vector but I'm not really sure. Mybe the resizing is done in a separate thread and the new insertion occurs before the vector is resized ... this is my best guess ...
    I also tested this in a pure J2SE evironment and I don't have the same strange behavior
    Can anybody tell me what I am doing wrong or how I could avoid this problem ?
    Thanks a lot !
    Cheers Alex

    Am i doing anything wrong?Uhm, yes. Read the API doc for addElement() and for addAll()

  • Better code for hashtables

    Hi all.
    I have a vector which contains a lot of string. Then i have another string which is called keyword. So, for example:
    Vector v = new Vector();
    v.add("Sam went to the hospital today");
    v.add("They told him he had the flu");
    v.add("The hospital had arranged now arranged a second meetin")
    v.add(" Sam will come back then");
    String Key =  " hospital;What i need to do is find in which vector position does hospital occur and give it a score. So i also need a way of storing the sentence again and assigning it a value i.e. (Sam went to the hospital today, 20). The value is preset. Any help would be much appreciated. Many thanks.

    hi,
    here i am giving example on hash table.
    please follow.
    import java.util.*;
    public class SortHashtable {
    public static void main(String[] args) {
    // Create and populate hashtable
    Hashtable ht = new Hashtable();
    ht.put("abc",new Double(3445.23));
    ht.put("xyz",new Double(2333.56));
    ht.put("pqr",new Double(3900.88));
    ht.put("mno",new Double(2449.00));
    // Sort hashtable.
    Vector v = new Vector(ht.keySet());
    Collections.sort(v);
    // Display (sorted) hashtable.
    for (Enumeration e = v.elements(); e.hasMoreElements();) {
    String key = (String)e.nextElement();
    System.out.println(key+":"+ht.get(key));
    System.out.println();
    i hope u get what u want
    jp reddy

  • Dynamic naming of Vectors

    Hi,
    I need to be able to create vectors dynamically, for
    example vectorName1, vectorName2 and so on. I've
    managed to do this with JButtons using setName().
    Is there a similar way to set the name of vectors
    using a string?
    Thanx

    why do you need dynamic names?
    you could use a vector of vector or a hashtable of vectors to dynamically allocate vectors, but naming them?
    a hashtable seems most appropriate since you could use your dynamic names as hash key.
    thomas

  • How to define Hashtable values, when the hashtable automatically grows?

    I have two hashtables in my code:
    Hashtable<String, Vector<SellerData>> productList
    Hashtable<String, Vector<String>> sellerList
    These hashtables are member variables of a class and they are defined in the constructor of that class. Also in the same constructor, there are loops that allocate memory for the vectors in these hashtables. However, the capacity of Java hashtables are automatically increased as more elements are inserted, I'm wondering how I can make sure Vectors in these newly added hashtable slots are also defined and have memory allocated for them?
    My current solution is that the user code does some checking to make sure vectors in above hashtables are defined, but I was wondering if there is some other way I could do this so the user code does not have to do any checking?
    Thanks,
    P.

    A few notes:
    1) Even though you assign a value to an attribute in the constructor, do NOT assume it will be assigned a value in your methods. Polymorphism will bite your behind on this one. Say you have the following class setup:class A {
      Integer a;
      public A() { X(); }
      public X() { // init code }
    class B extends A {
      public B()  { super(); a = new Integer(0); }
      public X() { System.err.println( a.toString() ); }
    }This will cause an exception since the constructor for B calls the constructor for A which calls B.X BEFORE you set a. Can't tell you how difficult it was to track this one down the first time it happened to me.
    But to your question! It is impossible unless you implement an extension for Hashtable as follows
    class MyHash extends Hashtable {
      // setup as a Hashtable<String, Vector> in constructor.
      public get(Object key) {
        Object ret = super.get( key );
        if ( ret = null )
          return new Vector();
        else
          return ret;
      // similar code for entrySet() and values()
      // if you need non-null values for these methods too.

  • Maximum open_cusors exceed error in oracle

    I am returning resultset object from many of my functions.After I run a few programmes i get "maximum no of cursors exceeded in oracle" error. I am not closing Statement obj also i am not closing reultset obj.Which one is to be closed to remove the above error. Also wont garbage collection of the statement which created the resultset in the called function cause my result to cease in existence . Also if i try to use getStatement() in the calling function i get a " operation not allowed " error
    What is the solution to my problem
    public Statement getStates(){
    Connection conn = null;
    SharedConnectionPool moConnPool = SharedConnectionPool.getInstance();
    ResultSet rsStateMast = null;
    ResultSet returnRSStateMast = null;
    Statement stmtStateMast = null;
    try{
    //Get state details
    conn = moConnPool.getConnection();
    stmtStateMast = conn.createStatement();
    String msStateMastQuery = "select csm_state_code, csm_state_name from cms_state_mast where csm_cntry_code = " + this.miCountryCode + "order by csm_state_name";
    moLogFile.writeToLog(CLASS_NAME,35,msStateMastQuery);
    rsStateMast = stmtStateMast.executeQuery(msStateMastQuery);
    returnRSStateMast = rsStateMast;
    // stmtStateMast.close();
    if (returnRSStateMast != null){
    return stmtStateMast;
    }//end of if
    }//end of try
    catch(SQLException sqe){
    throw new CMSException("Some SQL Exception occured " + sqe.toString(),sqe);
    }//end of catch
    finally{
    moConnPool.free(conn);
    return stmtStateMast;
    }//end of finally
    }//end of getStates
    Above is the function I am using
    I realise that my problem would be solved if I pass Statement to or from the function .
    But the problem is the I am more than halfway through the project and the chaging all functions in the above manner will be too time consuming . Is there no other solution ? . Why does the getStatement() method in ResultSet give a "method not supported Exception".
    Also will the statement obj in the called function be eligible for garbage collection ? Because that will close my ResultSet.
    I have already increased the limit of open cursors.
    What I want to know is ,whether closing all resultSets will sufficient for closing the open_cursors in Oracle or is it necessary to close all statements to close the open_cursors.
    In short whether cursors are related to statements or are they related to Resultsets.
    Also I want to know why are my resultSets and statements not getting garbage collected.Because if they would get Garbage collected then they would get closed ,and thus the open_cursors would be closed too.
    But then if the statement in the called func gets garbage collected while the resultSet object is still in use , then the resultSet would become null and a null pointer Exception will be thrown.
    Considering all this, do you feel it is mandatory for me to pass statements between the functions ? or is there any other awy out?
    Also why am i getting an "operation not allowed" exception when I try to use the function rs.getStatement() in order to get the parent statement so that it can be closed in the calling function.

    I am returning resultset object from many of my
    functions.After I run a few programmes i get "maximum
    no of cursors exceeded in oracle" error. I am not
    closing Statement obj also i am not closing reultset
    obj.Which one is to be closed to remove the above
    error. Also wont garbage collection of the statement
    which created the resultset in the called function
    cause my result to cease in existence . Also if i try
    to use getStatement() in the calling function i get a
    " operation not allowed " error
    What is the solution to my problem
    public Statement getStates(){
    Connection conn = null;
    SharedConnectionPool moConnPool =
    SharedConnectionPool.getInstance();
    ResultSet rsStateMast = null;
    ResultSet returnRSStateMast = null;
    Statement stmtStateMast = null;
    try{
    //Get state details
    conn = moConnPool.getConnection();
    stmtStateMast = conn.createStatement();
    String msStateMastQuery = "select csm_state_code,
    csm_state_name from cms_state_mast where
    csm_cntry_code = " + this.miCountryCode + "order by
    csm_state_name";
    moLogFile.writeToLog(CLASS_NAME,35,msStateMastQuery);
    rsStateMast =
    stmtStateMast.executeQuery(msStateMastQuery);
    returnRSStateMast = rsStateMast;
    // stmtStateMast.close();
    if (returnRSStateMast != null){
    return stmtStateMast;
    }//end of if
    }//end of try
    catch(SQLException sqe){
    throw new CMSException("Some SQL Exception occured " +
    sqe.toString(),sqe);
    }//end of catch
    finally{
    moConnPool.free(conn);
    return stmtStateMast;
    }//end of finally
    }//end of getStates
    Above is the function I am using
    I realise that my problem would be solved if I pass
    Statement to or from the function .Yes, you should close the statement. I used to have the same problem, and close the statement can fix it.
    >
    But the problem is the I am more than halfway through
    the project and the chaging all functions in the above
    manner will be too time consuming . Is there no other
    solution ? . Why does the getStatement() method in
    ResultSet give a "method not supported Exception".
    Also will the statement obj in the called function be
    eligible for garbage collection ? Because that will
    close my ResultSet.
    Afraid not, as connection object may hold a reference to it, and connection objects are in a pool, so the statement object will be there as long as the connection object's there.
    >
    I have already increased the limit of open cursors.
    What I want to know is ,whether closing all resultSets
    will sufficient for closing the open_cursors in Oracle
    or is it necessary to close all statements to close
    the open_cursors.
    Well, I don't know the inside code, but, as I experienced, the problem is you openned too many statement (conn.createStatement()), because you are using a connection pool, you may re-use a connection object many times, this is kind of like this:
    conn.createStatement();
    conn.createStatement();
    ..//a lot of themso you opened too many statement, and I suspect this is the problem according to my testing.
    In short whether cursors are related to statements or
    are they related to Resultsets.
    If you close the statement, the result set of it will be closed as well, but I don't think close result set could close statement.
    Also I want to know why are my resultSets and
    statements not getting garbage collected.Because if
    they would get Garbage collected then they would get
    closed ,and thus the open_cursors would be closed
    too.
    As I mentioned above, because you're using a connection pool, and unless you explicitly close statement object, its reference my be hold by the connection object and won't be garbage collected.
    But then if the statement in the called func gets
    garbage collected while the resultSet object is still
    in use , then the resultSet would become null and a
    null pointer Exception will be thrown.
    The statement is still there.
    Considering all this, do you feel it is mandatory for
    me to pass statements between the functions ? or is
    there any other awy out?
    Usually, you should return a collection (like HashTable or Vector etc.) instead of the result set, so, you can have one point control over the statement and result set object. But in you case, you have to track each statement object and close it.
    Also why am i getting an "operation not allowed"
    exception when I try to use the function
    rs.getStatement() in order to get the parent statement
    so that it can be closed in the calling function.
    This is not supported, at least in the libarary you're using.

  • Why do i get this error?

    Hi
    When i run my code i get this exception,
    java.lang.ClassCastException: java.lang.Integer
    at has33.main(has33.java:29)
    Why is it that i get this exception?
    And could some help me so that i doun't get this Exception?
    thanks
    nicky
    import java.io.*;
    import java.lang.*;
    import java.util.*;
    public class has33{
    public static void main(String[] args) {
    Hashtable ht = new Hashtable();
    //Add vector to store results
    Vector results = new Vector();
    Object value = null;
    int keys[] = {1,2,3,4,5,6,7,8,9,10};
    //System.out.println(keys);
    String values[] = {"ben", "ben", "alex", "alex", "matt","matt", "mum", "mum", "dad", "matt"};
    // First, map keys to values in a hashtable
    Hashtable hash = new Hashtable();
    // the code matches values one by one for each of the keys
    for(int i = 0; i < keys.length; i++) {
    hash.put(new Integer(keys), values[i]);
    // Then we find each value and remove it from the hashtable
    for(int j = 0; j < values.length; j++) {
    ht = (hash);
    value = (values[j]);
    Vector v = new Vector();
    String token = null;
    StringTokenizer st = null;
    if( ht.containsValue( value )) {
    Enumeration e = ht.keys();
    while (e.hasMoreElements()) {
    String tempkey = (String)e.nextElement();
    String tempvalue = (String)ht.get(tempkey);
    if (tempvalue.equals(value)) {
    v.add(tempkey);
    ht.remove(tempkey);

    No i mean to put then strings and Integers in hashtable like this
                             hash.put(new Integer(1), ben);
                             hash.put(new Integer(2), ben);
                             hash.put(new Integer(3), alex);
                             hash.put(new Integer(4), alex);
                             hash.put(new Integer(5), matt);
                             hash.put(new Integer(6), matt);
                             hash.put(new Integer(7), ben);
                             hash.put(new Integer(8), matt);
                             hash.put(new Integer(9), dad);
                                            hash.put(new Integer(10), dad);thanks
    nicky

  • Rename file extension during a file upload ??

    I need to rename the extension of a file at some point during the file upload. I am not sure where to do this at.
    The file needs to be renamed before it is written to the directory.
    Basically, the file will come in with a .txt or .doc type. Based on a users profile, I will change the type to a non-relavent number such as 1111.
    Here is my upload servlet. Can you tell me where to change the type so it will write the file with the new extension?
    Thanks.
    public class FileExport {
    //restrict upload files to 1 Meg
    private static final int DEFAULT_MAX_POST_SIZE = 1024 * 1024;
    private static final String NO_FILE = "unknown";
    private HttpServletRequest req;
    private File dir;
    private int maxSize;
    private Hashtable parameters = new Hashtable(); // name - Vector of values
    private Hashtable files = new Hashtable(); // name - UploadedFile
    public FileExport(HttpServletRequest request,
    String saveDirectory) throws IOException {
    this(request, saveDirectory, DEFAULT_MAX_POST_SIZE);
    // request the servlet request
    // saveDirectory = directory in which to save any uploaded files
    // maxPostSize = maximum size of the POST content
    public FileExport(HttpServletRequest request,
    String saveDirectory,
    int maxPostSize) throws IOException {
    // check values
    if (request == null)
    throw new IllegalArgumentException("request cannot be null");
    if (saveDirectory == null)
    throw new IllegalArgumentException("saveDirectory cannot be null");
    if (maxPostSize <= 0) {
    throw new IllegalArgumentException("maxPostSize must be positive");
    // Save the request, dir, and max size
    req = request;
    dir = new File(saveDirectory);
    maxSize = maxPostSize;
    // Check saveDirectory is truly a directory
    if (!dir.isDirectory())
    throw new IllegalArgumentException("Not a directory: " + saveDirectory);
    // Check saveDirectory is writable
    if (!dir.canWrite())
    throw new IllegalArgumentException("Not writable: " + saveDirectory);
    // Now parse the request saving data to "parameters" and "files";
    // write the file contents to the saveDirectory
    readRequest();
    public FileExport(ServletRequest request,
    String saveDirectory) throws IOException {
    this((HttpServletRequest)request, saveDirectory);
    public FileExport(ServletRequest request,
    String saveDirectory,
    int maxPostSize) throws IOException {
    this((HttpServletRequest)request, saveDirectory, maxPostSize);
    // Returns the names of all the parameters as an Enumeration of
    // Strings. It returns an empty Enumeration if there are no parameters.
    public Enumeration getParameterNames() {
    return parameters.keys();
    // Returns the names of all the uploaded files as an Enumeration of
    // Strings. It returns an empty Enumeration if there are no uploaded
    // files. Each file name is the name specified by the form, not by
    // the user.
    public Enumeration getFileNames() {
    return files.keys();
    // Returns the value of the named parameter as a String, or null if
    // the parameter was not sent or was sent without a value.
    public String getParameter(String name) {
    try {
    Vector values = (Vector)parameters.get(name);
    if (values == null || values.size() == 0) {
    return null;
    String value = (String)values.elementAt(values.size() - 1);
    return value;
    catch (Exception e) {
    return null;
    // Returns the values of the named parameter as a String array, or null if
    // the parameter was not sent.
    public String[] getParameterValues(String name) {
    try {
    Vector values = (Vector)parameters.get(name);
    if (values == null || values.size() == 0) {
    return null;
    String[] valuesArray = new String[values.size()];
    values.copyInto(valuesArray);
    return valuesArray;
    catch (Exception e) {
    return null;
    // Returns the filesystem name of the specified file, or null if the
    // file was not included in the upload. A filesystem name is the name
    // specified by the user. It is also the name under which the file is
    // actually saved.
    public String getFilesystemName(String name) {
    try {
    UploadedFile file = (UploadedFile)files.get(name);
    return file.getFilesystemName(); // may be null
    catch (Exception e) {
    return null;
    // Returns the content type of the specified file (as supplied by the
    //client browser), or null if the file was not included in the upload.
    public String getContentType(String name) {
    try {
    UploadedFile file = (UploadedFile)files.get(name);
    return file.getContentType(); // may be null
    catch (Exception e) {
    return null;
    // Returns a File object for the specified file saved on the server's
    // filesystem, or null if the file was not included in the upload.
    public File getFile(String name) {
    try {
    UploadedFile file = (UploadedFile)files.get(name);
    return file.getFile(); // may be null
    catch (Exception e) {
    return null;
    // method that actually parses the request.
    protected void readRequest() throws IOException {
    // Check the content length to prevent denial of service attacks
    int length = req.getContentLength();
    if (length > maxSize) {
    throw new IOException("Posted content length of " + length +
    " exceeds limit of " + maxSize);
    // Check the content type to make sure it's "multipart/form-data"
    // Access header two ways to work around WebSphere oddities
    String type = null;
    String type1 = req.getHeader("Content-Type");
    String type2 = req.getContentType();
    // If one value is null, choose the other value
    if (type1 == null && type2 != null) {
    type = type2;
    else if (type2 == null && type1 != null) {
    type = type1;
    // If neither value is null, choose the longer value
    else if (type1 != null && type2 != null) {
    type = (type1.length() > type2.length() ? type1 : type2);
    if (type == null ||
    !type.toLowerCase().startsWith("multipart/form-data")) {
    throw new IOException("Posted content type isn't multipart/form-data");
    // Get the boundary string; it's included in the content type.
    // Should look something like "------------------------12012133613061"
    String boundary = extractBoundary(type);
    if (boundary == null) {
    throw new IOException("Separation boundary was not specified");
    // Construct the special input stream we'll read from
    MultipartInputStreamHandler in =
    new MultipartInputStreamHandler(req.getInputStream(), length);
    // Read the first line, should be the first boundary
    String line = in.readLine();
    if (line == null) {
    throw new IOException("Corrupt form data: premature ending");
    // Verify that the line is the boundary
    if (!line.startsWith(boundary)) {
    throw new IOException("Corrupt form data: no leading boundary");
    // Now that we're just beyond the first boundary, loop over each part
    boolean done = false;
    while (!done) {
    done = readNextPart(in, boundary);
    // A utility method that reads an individual part. Dispatches to
    // readParameter() and readAndSaveFile() to do the actual work. A
    // subclass can override this method for a better optimized or
    // differently behaved implementation.
    protected boolean readNextPart(MultipartInputStreamHandler in,
    String boundary) throws IOException {
    // Read the first line, should look like this:
    // content-disposition: form-data; name="field1"; filename="file1.txt"
    String line = in.readLine();
    if (line == null) {
    // No parts left, we're done
    return true;
    else if (line.length() == 0) {
    // IE4 on Mac sends an empty line at the end; treat that as the end.
    // Thanks to Daniel Lemire and Henri Tourigny for this fix.
    return true;
    // Parse the content-disposition line
    String[] dispInfo = extractDispositionInfo(line);
    String disposition = dispInfo[0];
    String name = dispInfo[1];
    String filename = dispInfo[2];
    // Now onto the next line. This will either be empty
    // or contain a Content-Type and then an empty line.
    line = in.readLine();
    if (line == null) {
    // No parts left, we're done
    return true;
    // Get the content type, or null if none specified
    String contentType = extractContentType(line);
    if (contentType != null) {
    // Eat the empty line
    line = in.readLine();
    if (line == null || line.length() > 0) {  // line should be empty
    throw new
    IOException("Malformed line after content type: " + line);
    else {
    // Assume a default content type
    contentType = "application/octet-stream";
    // Now, finally, we read the content (end after reading the boundary)
    if (filename == null) {
    // This is a parameter, add it to the vector of values
    String value = readParameter(in, boundary);
    if (value.equals("")) {
    value = null; // treat empty strings like nulls
    Vector existingValues = (Vector)parameters.get(name);
    if (existingValues == null) {
    existingValues = new Vector();
    parameters.put(name, existingValues);
    existingValues.addElement(value);
    else {
    // This is a file
    readAndSaveFile(in, boundary, filename, contentType);
    if (filename.equals(NO_FILE)) {
    files.put(name, new UploadedFile(null, null, null));
    else {
    files.put(name,
    new UploadedFile(dir.toString(), filename, contentType));
    return false; // there's more to read
    // A utility method that reads a single part of the multipart request
    // that represents a parameter. A subclass can override this method
    // for a better optimized or differently behaved implementation.
    protected String readParameter(MultipartInputStreamHandler in,
    String boundary) throws IOException {
    StringBuffer sbuf = new StringBuffer();
    String line;
    while ((line = in.readLine()) != null) {
    if (line.startsWith(boundary)) break;
    sbuf.append(line + "\r\n"); // add the \r\n in case there are many lines
    if (sbuf.length() == 0) {
    return null; // nothing read
    sbuf.setLength(sbuf.length() - 2); // cut off the last line's \r\n
    return sbuf.toString(); // no URL decoding needed
    // A utility method that reads a single part of the multipart request
    // that represents a file, and saves the file to the given directory.
    // A subclass can override this method for a better optimized or
    // differently behaved implementation.
    protected void readAndSaveFile(MultipartInputStreamHandler in,
    String boundary,
    String filename,
    String contentType) throws IOException {
    OutputStream out = null;
    // A filename of NO_FILE means no file was sent, so just read to the
    // next boundary and ignore the empty contents
    if (filename.equals(NO_FILE)) {
    out = new ByteArrayOutputStream(); // write to nowhere
    // A MacBinary file goes through a decoder
    else if (contentType.equals("application/x-macbinary")){
    File f = new File(dir + File.separator + filename);
    out = new MacBinaryDecoderOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(f), 8 * 1024));
    // A real file's contents are written to disk
    else {
    File f = new File(dir + File.separator + filename);
    out = new BufferedOutputStream(new FileOutputStream(f), 8 * 1024);
    byte[] bbuf = new byte[100 * 1024]; // 100K
    int result;
    String line;
    // ServletInputStream.readLine()
    // adds a \r\n to the end of the last line.
    // Since we want a byte-for-byte transfer, we have to cut those chars.
    boolean rnflag = false;
    while ((result = in.readLine(bbuf, 0, bbuf.length)) != -1) {
    // Check for boundary
    if (result > 2 && bbuf[0] == '-' && bbuf[1] == '-') { // quick pre-check
    line = new String(bbuf, 0, result, "ISO-8859-1");
    if (line.startsWith(boundary)) break;
    // Are we supposed to write \r\n for the last iteration?
    if (rnflag) {
    out.write('\r'); out.write('\n');
    rnflag = false;
    // Write the buffer, postpone any ending \r\n
    if (result >= 2 &&
    bbuf[result - 2] == '\r' &&
    bbuf[result - 1] == '\n') {
    out.write(bbuf, 0, result - 2); // skip the last 2 chars
    rnflag = true; // make a note to write them on the next iteration
    else {
    out.write(bbuf, 0, result);
    out.flush();
    out.close();
    // Extracts and returns the boundary token from a line.
    private String extractBoundary(String line) {
    // Use lastIndexOf() because IE 4.01 on Win98 has been known to send the
    // "boundary=" string multiple times. Thanks to David Wall for this fix.
    int index = line.lastIndexOf("boundary=");
    if (index == -1) {
    return null;
    String boundary = line.substring(index + 9); // 9 for "boundary="
    // The real boundary is always preceeded by an extra "--"
    boundary = "--" + boundary;
    return boundary;
    // Extracts and returns disposition info from a line, as a String array
    // with elements: disposition, name, filename. Throws an IOException
    // if the line is malformatted.
    private String[] extractDispositionInfo(String line) throws IOException {
    // Return the line's data as an array: disposition, name, filename
    String[] retval = new String[3];
    // Convert the line to a lowercase string without the ending \r\n
    // Keep the original line for error messages and for variable names.
    String origline = line;
    line = origline.toLowerCase();
    // Get the content disposition, should be "form-data"
    int start = line.indexOf("content-disposition: ");
    int end = line.indexOf(";");
    if (start == -1 || end == -1) {
    throw new IOException("Content disposition corrupt: " + origline);
    String disposition = line.substring(start + 21, end);
    if (!disposition.equals("form-data")) {
    throw new IOException("Invalid content disposition: " + disposition);
    // Get the field name
    start = line.indexOf("name=\"", end); // start at last semicolon
    end = line.indexOf("\"", start + 7); // skip name=\"
    if (start == -1 || end == -1) {
    throw new IOException("Content disposition corrupt: " + origline);
    String name = origline.substring(start + 6, end);
    // Get the filename, if given
    String filename = null;
    start = line.indexOf("filename=\"", end + 2); // start after name
    end = line.indexOf("\"", start + 10); // skip filename=\"
    if (start != -1 && end != -1) {                // note the !=
    filename = origline.substring(start + 10, end);
    // The filename may contain a full path. Cut to just the filename.
    int slash =
    Math.max(filename.lastIndexOf('/'), filename.lastIndexOf('\\'));
    if (slash > -1) {
    filename = filename.substring(slash + 1); // past last slash
    if (filename.equals("")) filename = NO_FILE; // sanity check
    // Return a String array: disposition, name, filename
    retval[0] = disposition;
    retval[1] = name;
    retval[2] = filename;
    return retval;
    // Extracts and returns the content type from a line, or null if the
    // line was empty. Throws an IOException if the line is malformatted.
    private String extractContentType(String line) throws IOException {
    String contentType = null;
    // Convert the line to a lowercase string
    String origline = line;
    line = origline.toLowerCase();
    // Get the content type, if any
    if (line.startsWith("content-type")) {
    int start = line.indexOf(" ");
    if (start == -1) {
    throw new IOException("Content type corrupt: " + origline);
    contentType = line.substring(start + 1);
    else if (line.length() != 0) {  // no content type, so should be empty
    throw new IOException("Malformed line after disposition: " + origline);
    return contentType;
    // A class to hold information about an uploaded file.
    class UploadedFile {
    private String dir;
    private String filename;
    private String type;
    UploadedFile(String dir, String filename, String type) {
    this.dir = dir;
    this.filename = filename;
    this.type = type;
    public String getContentType() {
    return type;
    public String getFilesystemName() {
    return filename;
    public File getFile() {
    if (dir == null || filename == null) {
    return null;
    else {
    return new File(dir + File.separator + filename);
    // A class to aid in reading multipart/form-data from a ServletInputStream.
    // It keeps track of how many bytes have been read and detects when the
    // Content-Length limit has been reached.
    class MultipartInputStreamHandler {
    ServletInputStream in;
    int totalExpected;
    int totalRead = 0;
    byte[] buf = new byte[8 * 1024];
    public MultipartInputStreamHandler(ServletInputStream in,
    int totalExpected) {
    this.in = in;
    this.totalExpected = totalExpected;
    // Reads the next line of input. Returns null to indicate the end
    // of stream.
    public String readLine() throws IOException {
    StringBuffer sbuf = new StringBuffer();
    int result;
    String line;
    do {
    result = this.readLine(buf, 0, buf.length); // this.readLine() does +=
    if (result != -1) {
    sbuf.append(new String(buf, 0, result, "ISO-8859-1"));
    } while (result == buf.length); // loop only if the buffer was filled
    if (sbuf.length() == 0) {
    return null; // nothing read, must be at the end of stream
    sbuf.setLength(sbuf.length() - 2); // cut off the trailing \r\n
    return sbuf.toString();
    // A pass-through to ServletInputStream.readLine() that keeps track
    // of how many bytes have been read and stops reading when the
    // Content-Length limit has been reached.
    public int readLine(byte b[], int off, int len) throws IOException {
    if (totalRead >= totalExpected) {
    return -1;
    else {
    if (len > (totalExpected - totalRead)) {
    len = totalExpected - totalRead; // keep from reading off end
    int result = in.readLine(b, off, len);
    if (result > 0) {
    totalRead += result;
    return result;
    // Class to filters MacBinary files to normal files on the fly
    // Optimized for speed more than readability
    class MacBinaryDecoderOutputStream extends FilterOutputStream {
    int bytesFiltered = 0;
    int dataForkLength = 0;
    public MacBinaryDecoderOutputStream(OutputStream out) {
    super(out);
    public void write(int b) throws IOException {
    // Bytes 83 through 86 are a long representing the data fork length
    // Check <= 86 first to short circuit early in the common case
    if (bytesFiltered <= 86 && bytesFiltered >= 83) {
    int leftShift = (86 - bytesFiltered) * 8;
    dataForkLength = dataForkLength | (b & 0xff) << leftShift;
    // Bytes 128 up to (128 + dataForkLength - 1) are the data fork
    else if (bytesFiltered < (128 + dataForkLength) && bytesFiltered >= 128) {
    out.write(b);
    bytesFiltered++;
    public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
    public void write(byte b[], int off, int len) throws IOException {
    // If the write is for content past the end of the data fork, ignore
    if (bytesFiltered >= (128 + dataForkLength)) {
    bytesFiltered += len;
    // If the write is entirely within the data fork, write it directly
    else if (bytesFiltered >= 128 &&
    (bytesFiltered + len) <= (128 + dataForkLength)) {
    out.write(b, off, len);
    bytesFiltered += len;
    // Otherwise, do the write a byte at a time to get the logic above
    else {
    for (int i = 0 ; i < len ; i++) {
    write(b[off + i]);

    I am also need to rename a file and extension while uploadinf the file to the server. The oreilly example seems only save as the same file name and ext. I wonder if you have the ability chANGE OIT OR NOT. pLEASE LET ME KNOW
    thanks
    kansen

  • I need a suggestion - Object to XML, XML to object

    Hi everyone,
    I've made a tool that stores objects into an XML document. It's a serialization process, I guess. It works well, but I have a problem, that may be impossible to solve:
    When I restore an object from the XML document, I need to instantiate new objects all the time. Consider this:
    This class:
    public class ScreenConfiguration
        private int width = 1024;
        private int height = 768;
        private int resolution = 96;
        private int colorDepth = 32;
    }would become
    <object class="ScreenConfiguration" version="1a">
    <width>1024</width>
    <height>768</height>
    <resolution>96</resolution>
    <colorDepth>32</colorDepth>
    </object>
    So far, so good, right? The problem is when I want to restore an object.
    If the ScreenConfiguration class would have this constructor:
    ScreenConfiguration(int width, int height, int resolution, int colorDepth)I would not be able to instantiate the class without passing the correct parameters. And it's impossible to determine the correct parameters. Is there any way you can instantiate a class without letting it run any initializing code? I'm guessing that this problem is impossible to overcome, but there's no harm in asking... Any suggestions?
    Thanks on advance,
    Nille

    I was a bit unclear while describing the problem. The example provided is very very very simple. The problem isn't these kinds of classes, but more complex classes, such as Hashtables and Vectors that that contains fields that requires parameters while being instantiated. I don't really care about the initialization process - once I have an object I can restore it's fields and it won't know it's been restored from an XML file.
    To clearify the problem, consider this class:
    public class ATestClass
       Integer myTestField = new Integer(15);
    }Serializing this class is no problem: the Integer object simply contains a value-field that can be serialized without any problem. When restoring the object I want to create an integer and set its 'value' field, but since there is no default constructor, this is not prossible. You are not obligated to provide a default constructor in java, but is there anyway to use one even though it's not there? It seems far-fetched, but I'm trying anything right know...

  • A question on JInternalFrame of Swing. Let see the code

    Hello everybody,
    I am setting up a Frame that contains 2 JInternalFrames in its desktopPane. The first JInternalFrame is to show the map. The second one have some check box. What I wanna do is, when I check the CheckBox in the second JInternalFrame, after getting the result from Database, it show the result on Map. The result will be some red ellipses on the first JInternalFrame.
    The code work well with Database. But I really need your help to do with the event on InternalFrame
    Thanks in advance !
    Quin,
    Here is the code of the main Frame:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.io.*;
    import java.net.*;
    import java.beans.*;
    public class MapLocator
         public static void main(String [] args)
              JFrame frame = new DesktopFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    Create a desktop frames that contains internal frame
    class DesktopFrame extends JFrame implements ActionListener
         public DesktopFrame()
              super("Map Locator v.1.0.0");
              this.setSize(new Dimension(WIDTH,HEIGHT));
              desktop = new JDesktopPane();
              this.setContentPane(desktop);
              this.createInternalFrame(
                   new mapPanel(),"Ban do Thanh pho Ho Chi Minh",0,0,480,515);
              this.createInternalFrame(
                   new commandPanel(),"Chu thich va tim kiem",480,0,320,515);
    Create an internal frame on the desktop.
    @param c the component to display in the internal frame
    @param t the title ofthe internal frame.
         public void createInternalFrame(JPanel c, String t,int ifx, int ify, int ifwidth, int ifheight)
                 final JInternalFrame iframe = new JInternalFrame(t,
                 true//resizeable
                 ,true//closable
                 ,true//maximizable
                 ,true//iconifiable
                 iframe.getContentPane().add(c);
                 desktop.add(iframe);
                 iframe.setFrameIcon(new ImageIcon("new.gif"));
                 //add listener to confirm frame closing
                 iframe.addVetoableChangeListener(new VetoableChangeListener()
                      public void vetoableChange(PropertyChangeEvent event)
                           throws PropertyVetoException
                           String name = event.getPropertyName();
                           Object value = event.getNewValue();
                           //we only want to check attempts to close a frame
                           if(name.equals("closed") && value.equals(Boolean.TRUE))
                                //ask user if it is ok to close
                                int result =
                      JOptionPane.showInternalConfirmDialog(iframe,"OK to close");
                                //if the user doesn't agree, veto the close
                                if(result != JOptionPane.YES_OPTION)
                      throw new PropertyVetoException("User cancel the close",event);
                 iframe.setVisible(true);
                 iframe.setLocation(ifx,ify);
                 iframe.setSize(new Dimension (ifwidth, ifheight));
         private static final int WIDTH = 800;
         private static final int HEIGHT = 600;
         private JDesktopPane desktop;
         private int nextFrameX;
           private int nextFrameY;
            private int frameDistance;
         private JMenuBar menuBar;
         private JMenu fileMenu, viewMenu, searchMenu, windowMenu, helpMenu;
         private JRadioButtonMenuItem javalaf, liquidlaf, motiflaf, windowlaf, threedlaf;
    }Below is the code of first JInternalFrame
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.util.Random;
    import java.util.*;
    import com.sun.image.codec.jpeg.*;
    Create a canvas that show a map
    public class mapPanel extends JPanel
         implements MouseMotionListener, MouseListener
         public mapPanel()
              addMouseMotionListener(this);
              addMouseListener(this);
    Unbarrier the comment below to see how the map model work
    //Unbarrier this to see -->
             try
                InputStream in = getClass().getResourceAsStream(nameOfMap);
                JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
                mImage = decoder.decodeAsBufferedImage();
                in.close();//Close dong nhap
              catch(ImageFormatException ie)
              { System.out.println ("Error on formating image");}
              catch(IOException ioe)
              { System.out.println ("Error on input/ouput image");}
              catch(Exception e){}
    Connect to database
              connDB();
              String addQuery = "";
              try
              Get the relation amongs points
                   int idStart = 0;
                   int idEnd = 0;
                   addQuery ="SELECT IDStart, IDEnd FROM 2Diem";
                   rs = stmt.executeQuery(addQuery);
                   int incre = 0;
                   while(rs.next())
                        idStart = rs.getInt(1);
                        Rel.add(incre, new Integer(idStart));
                        incre ++;
                        idEnd = rs.getInt(2);
                        Rel.add(incre, new Integer(idEnd));
                        incre ++;
         Load the Coordination of the points to hash table
                   int idPoint = 0;
                   int XP = 0;
                   int YP = 0;
                   addQuery ="SELECT IDDiem, CoorX, CoorY FROM Diem";
                   rs = stmt.executeQuery(addQuery);     
                   while(rs.next())
                        idPoint = rs.getInt(1);
                        XP = rs.getInt(2);
                        YP = rs.getInt(3);
                        hashX.put(new Integer(idPoint), new Integer(XP));
                        hashY.put(new Integer(idPoint), new Integer(YP));
         Create Points to draw the Line
                   line = new Line2D[(Rel.size())/2];
                   for(int i = 0, k = 0; i < Rel.size();i++, k = k+2)
                        X1 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y1 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        i++;
                        X2 = Integer.parseInt(""+hashX.get(Rel.elementAt(i)));
                        Y2 = Integer.parseInt(""+hashY.get(Rel.elementAt(i)));
                        line[k/2] = new Line2D.Double(X1,Y1,X2,Y2);
              catch(SQLException sqle){}
         private Hashtable hashX = new Hashtable();
         private Hashtable hashY = new Hashtable();
         private Vector Rel = new Vector(100,10);
         private Vector vecBackX = new Vector(10,2);
         private Vector vecBackY = new Vector(10,2);
         private int X1 = 0, X2 = 0, Y1 = 0, Y2 = 0;
         Draw the image to show
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D) g;
              g2.setRenderingHint(
                   RenderingHints.KEY_ANTIALIASING,
                   RenderingHints.VALUE_ANTIALIAS_ON);
        //     g2.drawImage(mImage,0,0,null);
        Paint the background with light Gray
              g2.setPaint(Color.lightGray);
              g2.fill(new Rectangle2D.Double(0,0,480,480));          
             fillBack(g2);
        Draw the street with its border is white, its background is orange
             g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(14,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
              g2.setPaint(Color.orange);
              g2.setStroke(new BasicStroke(10,BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
              for(int k = 0; k < Rel.size()/2; k++)
                   g2.draw(line[k]);
         Draw the grid on map
              g2.setPaint(Color.white);
              g2.setStroke(new BasicStroke(1));
              drawGrid(g2);
              if(point != null)
                   g2.setPaint(Color.red);
                   g2.fillOval(point.x - 3, point.y - 3, 7, 7);
    Draw the Background with tree and water
    @param g2 the Graphics2D that used to draw shapes
         private void fillBack(Graphics2D g2)
              Draw the background for map
              try
                   int BackX = 0;
                   int BackY = 0;
                   int incre = 0;
                   backGround = new GeneralPath[3];
                   for(int idBack = 1; idBack <= 3; idBack++)
    Since we use the vector for each background(tree / water), we have to
    refresh the vector before it can add new path inside
                        vecBackX.clear();
                        vecBackY.clear();
                        String addQuery = "SELECT CoorX, CoorY FROM BackCoor WHERE "
                        + " IDBack =" + idBack;
                        rs = stmt.executeQuery(addQuery);
                        while(rs.next())
                             BackX = rs.getInt(1);
                             BackY = rs.getInt(2);
    This will take the point into vector
                             vecBackX.add(incre,new Integer(BackX));
                             vecBackY.add(incre,new Integer(BackY));
                             incre++;
    Design the shapes of path
                             backGround[(idBack - 1)] =
                                  new GeneralPath(GeneralPath.WIND_EVEN_ODD);
                             backGround[(idBack - 1)].moveTo(
                                  Integer.parseInt(""+vecBackX.elementAt(0)),
                                  Integer.parseInt(""+vecBackY.elementAt(0)));
                             for(int i = 1; i < vecBackX.size(); i++)
                                  backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(i)),
                                       Integer.parseInt(""+vecBackY.elementAt(i)));
                             backGround[(idBack - 1)].lineTo(
                                       Integer.parseInt(""+vecBackX.elementAt(0)),
                                       Integer.parseInt(""+vecBackY.elementAt(0)));
                             backGround[(idBack - 1)].closePath();
    Here we have 3 Path that represented to tree and water
    The first and second one is tree.
    The last one is water.
    Draw the path now
                             if(idBack == 3)
                                  g2.setPaint(Color.cyan);
                                  g2.fill(backGround[(idBack - 1)]);
                             else
                                  g2.setPaint(Color.green);
                                  g2.fill(backGround[(idBack - 1)]);
                             incre = 0;
              catch(SQLException sqle)
                   System.out.println ("Khong ve duoc back ground");
    Create the grid on map
    @param g2 the Graphics2D that used to draw shapes
         private void drawGrid(Graphics2D g2)
              try
                 String Query =
                 "SELECT * FROM Grid";
                 rs = stmt.executeQuery(Query);
                 GridX = new Vector(100,2);
                 GridY = new Vector(100,2);
                 GridW = new Vector(100,2);
                 GridH = new Vector(100,2);
                 int incr = 0;
                 while(rs.next())
                      gridX = rs.getInt(2);
                      gridY = rs.getInt(3);
                      gridW = rs.getInt(4);
                      gridH = rs.getInt(5);
                      GridX.add(incr, new Integer(gridX));
                      GridY.add(incr, new Integer(gridY));
                      GridW.add(incr, new Integer(gridW));
                      GridH.add(incr, new Integer(gridH));
                      incr ++;
                 rec = new Rectangle2D.Double[GridX.size()];
                 for(int i = 0; i < GridX.size(); i++)
                      gridX = Integer.parseInt(""+GridX.elementAt(i));
                      gridY = Integer.parseInt(""+GridY.elementAt(i));
                      gridW = Integer.parseInt(""+GridW.elementAt(i));
                      gridH = Integer.parseInt(""+GridH.elementAt(i));
                      rec[i] = new Rectangle2D.Double(gridX, gridY, gridW, gridH);
                      g2.draw(rec);
    catch(SQLException sqle){}
    private Vector GridX, GridY, GridW, GridH;
    private int gridX = 0, gridY = 0, gridW = 0, gridH = 0;
    Fill the point
         public void placePoint(Graphics2D g2,Point p)
              g2.setPaint(Color.red);
              g2.fill(new Ellipse2D.Double(p.x - 3, p.y - 3, 7,7));
    Create connection to Database
         public void connDB()
              System.out.println ("Connecting to Database");
              String fileName = "Pro.mdb";
              String data = "jdbc:odbc:Driver={Microsoft Access Driver " +
         "(*.mdb)};DBQ=" + fileName + ";DriverID=22";
              try
                   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                   conn = DriverManager.getConnection(data,"","");
                   stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                        ResultSet.CONCUR_UPDATABLE);
              catch(ClassNotFoundException ce)
              { System.out.println ("Khong tim thay Driver"); }
              catch(SQLException sqle)
              { System.out.println ("Loi SQL trong khi Connect"); }
              Statement stmt = null;
              ResultSet rs = null;
              Connection conn = null;     
    This one is the model map to draw
         private String nameOfMap = "map.jpg";
         private BufferedImage mImage;
    Initialize the path and shapes to draw
         private Line2D line[];
         private Rectangle2D.Double rec[];
         private GeneralPath backGround[];
         private Point point;
         private int changeColor = 0;
    The last one is:
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.sql.*;
    public class commandPanel extends JPanel implements ActionListener
    Initial check box
         JCheckBox uyBanNhanDan = new JCheckBox();
         JCheckBox nganHang = new JCheckBox();
         JCheckBox buuDien = new JCheckBox();     
         JCheckBox khachSan = new JCheckBox();     
         JCheckBox benhVien = new JCheckBox();          
         JCheckBox cho = new JCheckBox();     
         JCheckBox nhaHat = new JCheckBox();     
         JCheckBox daiHoc = new JCheckBox();     
         JCheckBox thuvien = new JCheckBox();     
         JCheckBox nhaTho = new JCheckBox();     
         public commandPanel()
              this.setLayout(new BorderLayout());
              this.setBorder(BorderFactory.createCompoundBorder(
                          BorderFactory.createTitledBorder("***Chu dan***"),
                          BorderFactory.createEmptyBorder(5,5,5,5)));
    Create the combobox to show information
              uyBanNhanDan.setText("Uy Ban ND Quan");
              nganHang.setText("Ngan Hang");
              buuDien.setText("Buu Dien");
              khachSan.setText("Khach San");
              benhVien.setText("Benh Vien");
              cho.setText("Cho - Mua Sam");
              nhaHat.setText("Nha Hat");
              daiHoc.setText("Dai Hoc - Dao Tao");
              thuvien.setText("Thu Vien - Nha Sach");
              nhaTho.setText("Nha Tho - Chua");
              uyBanNhanDan.addActionListener(this);
              nganHang.addActionListener(this);
              buuDien.addActionListener(this);
              khachSan.addActionListener(this);
              benhVien.addActionListener(this);
              cho.addActionListener(this);
              nhaHat.addActionListener(this);
              daiHoc.addActionListener(this);
              thuvien.addActionListener(this);
              nhaTho.addActionListener(this);
              uyBanNhanDan.setActionCommand("1");
              nganHang.setActionCommand("2");
              buuDien.setActionCommand("3");
              khachSan.setActionCommand("4");
              benhVien.setActionCommand("5");
              cho.setActionCommand("6");
              nhaHat.setActionCommand("7");
              daiHoc.setActionCommand("8");
              thuvien.setActionCommand("10");
              nhaTho.setActionCommand("11");
              JPanel secP = new JPanel();
              secP.setLayout(new GridLayout(5,2));
              secP.add(uyBanNhanDan);
              secP.add(nganHang);
              secP.add(buuDien);
              secP.add(khachSan);
              secP.add(benhVien);
              secP.add(cho);
              secP.add(nhaHat);
              secP.add(daiHoc);
              secP.add(thuvien);
              secP.add(nhaTho);
              this.add(secP,BorderLayout.NORTH);
         public void actionPerformed(ActionEvent event)
              int x = 0;
              int y = 0;
              try
                   mapPanel mp = new mapPanel();
                   int idDiaDanh = 0;
                   if(event.getActionCommand() == "1")
                        idDiaDanh = 1;
                   String Query =
                   "SELECT CoorX, CoorY FROM MoTa WHERE IDDiaDanh =" + idDiaDanh;
                   mp.rs = mp.stmt.executeQuery(Query);
                   while(mp.rs.next())
    /*I have problem here*/
    /*Process the event for me*/          x = mp.rs.getInt(1);
                        y = mp.rs.getInt(2);
                        Graphics g2 = mp.getGraphics();
                        mp.paintComponents(g2);
                             g2.setPaint(Color.red);
                             g2.fill(new Ellipse2D.Double(x - 3, y - 3, 7, 7));     
              catch(SQLException sqle){}

    Strings are Objects.
    String[] strings = new String[3];
    String[0]="abcde";Right here, you are initializing the String array, and the String at index 0.
    JButton[] buttons = new JButton[2];
    buttons[0].setText("abcde");Right here, you are initializing the JButton array, but not any of the JButtons in the array. You then try to use the setText() method on a null JButton.

  • Mapping some integers

    hello
    I have this code below which maps out my string keys with string values; once it has maped them out it gets the string keys in the order that they are maped out at.
    my problem is that i want to map some integers out with them ( int keys[]={0,1,2,3,4,5,6,7,8,9} )
    How would i do this?
    please help me
    nicky
    Hashtable ht2 = new Hashtable();
    //Add vector to store results
    Vector results2 = new Vector();
    Object value2 = null;
    String keys2[] = {"FirstName", "LastName", "Id", "Addr1", "Phone","County", "Postcode", "Country", "Addr2", "Town"};
    //System.out.println(keys2);
    String values2[] = {"ben", "ben", "ben", "mum", "ben","mum", "ben", "ben", "mum", "mum"};
    // First, map keys to values in a hashtable
    Hashtable hash2 = new Hashtable();
    // the code matches values one by one for each of the keys
    for(int i = 0; i < keys2.length; i++) {
    hash2.put(keys2, values2[i]);
    // Then we find each value and remove it from the hashtable
    for(int j = 0; j < values2.length; j++) {
    ht2 = (hash2);
    value2 = (values2[j]);
    Vector v = new Vector();
    if( ht2.containsValue( value2 )) {
    Enumeration e = ht2.keys();
    while (e.hasMoreElements()) {
    String tempkey2 = (String)e.nextElement();
    String tempvalue2 = (String)ht2.get(tempkey2);
    if (tempvalue2.equals(value2)) {
                             v.add(tempkey2);
                             ht2.remove(tempkey2);
    results2.add(v);

    As you probably know you cannot use integers as keys in your Hashtable object, because the keys have to be objects and int is a primitive type, not an object.
    Use the Integer wrapper class:
    Hashtable ht = new Hashtable();
    ht.put(new Integer(1), "number one");
    ht.put(new Integer(2), "number two");
    To lookup a string:
    int key = 2;
    String value = (String)ht.get(new Integer(key));
    Jesper

Maybe you are looking for

  • Two people using the same itunes

    my brother and i have two ipods,but i cant get songs that i dowload on my ipod, but he can. how do i fix this?

  • HP Laserjet printer problem

    My HP Color Laserjet 1500 printer doesn't work properly with my Mac (it did work well formerly with a PC). There are two problems: 1) the software is incomplete: I do have the printer established as my default printer but I don't get the full range o

  • My laptop quit so how do I connect my ipad and iPhone to the new one and make it work?

    My laptop quit so how do I connect my ipad and iPhone to the new one and make it work?

  • Defining keys for the web

    Can anyone please let me know if it is possible to redefine keys for web forms. I can do this for the client/server version of the application but no for the web application. I have tried editing the FMRWEB.res file but cannot access it using Oracle

  • Source of Time-off Request Project

    Hi, I am new to CAF guided procedures, I am trying to implement the Callableobject in webdynpro(java) same as time-off request. in gallery>examples>Time-offrequset, will clear my doubts. so how can i get the DCs              com.sap.caf.eu.gp.example