Hashtable question

server:
  public void sendData(String data) {
    try {
      packages.put("server", new String(data));
      output.writeObject(packages);
      output.flush();
      packages.remove("server");
    catch (IOException cnfex) {
      control.text2.append("\nError writing object");
  }client:
          packages = (Hashtable) input.readObject();
          Enumeration e = packages.keys();
          String key = (String) e.nextElement();
          if(key.equals("assign")) {
            value = (Integer) packages.get("assign");
            label.setText("Connection successful! This is client " + value + ".");
          if(key.equals("server")) {
            String message = (String) packages.get("server");
            label.setText(message);
            packages.remove("server");
          }When I send data from server to client, it works at first time. Then I send the data to the client again. It doesn't work. Why?

server:
  public void sendData(String data) {
    try {
      packages.put("server", new String(data));
      output.writeObject(packages);
      output.flush();
      packages.clear();
    catch (IOException cnfex) {
      control.text2.append("\nError writing object");
  }client:
          // The bug is here! The packages is empty!
          packages = (Hashtable) input.readObject();
          Enumeration e = packages.keys();
          String key = (String) e.nextElement();
          if(key.equals("assign")) {
            value = (Integer) packages.get("assign");
            label.setText("Connection successful! This is client " + value + ".");
            packages.clear();
          if(key.equals("server")) {
            String message = (String) packages.get("server");
            label.setText(message);
            packages.clear();
          }I detect that the packages is empty in the client after the server sends the packages to the client. Anyone can solve this problem for me?

Similar Messages

  • Hashtable questions

    First Question: Is it possible to have a key and a value in a hashtable be different types?
    Code:
    public void newEntry(String key) {
    Hashtable htable;
    htable = new Hashtable();
    htable.put("LOW", 0);
    }Compile Error I got:
    cannot resolve symbol
    symbol  : method put  (java.lang.String,int)
    location: class java.util.Hashtable
            htable.put("LOW", 0);
    Second Question: Is it possible to have a hashtable as a value of a key of another hashtable?
    Code:
    public HashTable outerTable;
    public void newClient(int outerkey) {
    Hashtable inner;
    inner = new Hashtable();
    outerTable.put(outerkey, inner);
    public int getInner1 (int outerkey) {
    int num;
    Hashtable innerTable;
    innerTable = (Hashtable) outerTable.get(outerkey);
    num = (int) innerTable.get(1);
    return num;
    } Compile error I got:
    inconvertible types
    found   : java.lang.Object
    required: int
            num = (int) innerTable.get(1);hagen

    Yes, keys and values can be of different types, and
    yes, one Hashtable can be a key in another Hashtable
    (although I'd question the value of that). Any Object
    can be a key, and any Object can be a value. However,
    you can't use primitives for keys or values (you're
    trying to use int). You'll need to wrap the int in an
    Integer, or else turn it into a String. (I'd recommend
    the first, but the second will also work, if you can
    find some reason why it's more appropriate for you.)Thanks for the help...
    sorry... but concerning Hashtable within a hashtable, I meant a hashtable as a value of another hashtable, not a key. Basically what I'm trying to do is implement a server where it keeps track of clients and their requests and their response messages. So basically, i have the client id as the key of the outer hashtable and an inner hashtable for the value of the outer hashtable. Thus each client will have their own inner hashtable.
    In the inner hashtable, i have the sequence numbers of the client request as the key and the responses (once the server computes the answers) as the value of the hashtable.
    just wondering if there was an easier way of implementing this than the approach i have taken. Any suggestions would be greatly appreciated!

  • Quick Hashtable question

    Hello all, before hand thank you if you are able to assist. My question is that I have a two DB (SQL) strings 1 and 2. 1 has people and 2 has the account of the person. so data is like this...
    person account
    alex 20001
    alex 56547
    maria 879787
    maria 65464
    maria 789789
    I want to put then in a hashtable where with the associated string alex then his accounts pop up or maria her accounts pop up (and if i get this then i can do a reverse hash of that).
    Is there way to put the in easily in a method or do I have to do...
    table.put("alex","accountId"); ????
    Message was edited by:
    h2opologirly69

    I get an error in my code for some reason on this any idea?
    static HashMap<ArrayList[], ArrayList[]> idents=new HashMap<ArrayList[],ArrayList[]>();
    public static //what i put here? fillSymbol()
         Connection con=getConnection();
         ArrayList listofsymbols = null;
         try {
              statement = con.createStatement();
              String query=" exec a query  @flag='id'";
              ArrayList listofaccntid=null;
              listofaccntid=new ArrayList();
              ResultSet results=statement.executeQuery(query);
              //  System.out.println(results);
           //listofsymbols=new ArrayList();
            while (results.next())
                  traderID=results.getString(1);
                  String accountID=results.getString(2);
                //System.out.println(traderID);
                //System.out.println(accountID);
                listofsymbols.add(traderID);
                  listofaccntid.add(accountID);
                  idents.put(listofsymbols,listofaccntid);
                     //get error here??
         } catch (SQLException e1) {
              e1.printStackTrace();
         return //somthing here.

  • Very simple Hashtable question

    Ok, this might be a very dumb one, but I can't spot the error. After seeing numerous examples of a hashtable, I tried the following:
    Hashtable p = new Hashtable();
    p.put ("Alberta", "ab");
    But I keep getting the following error:
    <identifier> expected
    p.put ("Alberta", "ab");
    Can anyone tell me what I'm doing wrong???

    It's not a problem with hashtables, specificly. you can't add elements to an hash or a vector or perform another routine outside a method or a constructor. there is no way that
    that operation can be executed during compiling.
    regards

  • HashTable

    Hi guys,
    I was asked this question in the interview. I just wanted to know a better answer.
    Q. What are hashtables? How does it work internally.
    If you have 1 million values in Hashtables, being a key-pair value, does it generate 1 million hashcodes. How does it work.
    My answer was:
    I told Hashtables are data structures that help us perform lookup. They store key-value pair and are synchronized. The vales are stored by calculating the hashcode. (after that i was asked the 1 million values ques)
    I replied that it does not generate 1 million hashcodes. There might be many hash codes that are same. In that case the values with the same hash code are stored using linked lists one after the another.
    Can anyone gimme some better answer and temme if I was right. I have always been asked this 1 million values in hashtable questions. If anyone has some other related questions, it would be very helpful if they could post them here.
    Thanks!
    P

    Hey,
    Thank you for that link. It was indeed useful !
    P

  • NullPointer with Hashtable

    Hi,
    public class Questionnaire {
        public String userID = "";
        public String laptopDesktop;
        public String location;
        public Hashtable questions;
        public String othercomments;
        public Questionnaire() {
            this.questions.put("abc","123");
        ......// more code //// ...
        When the Questionnaire object is created using:
    Questionnaire q = new Questionnaire();
    I get a NullPointerException on the constructor.
    Please to help me understand this.
    thanks

    Nightman150 wrote:
    This will work:
    public class Questionnaire {
    public String userID = "";
    public String laptopDesktop;
    public String location;
    public Hashtable questions = new Hashtable() ;
    public String othercomments;
    public Questionnaire() {
    this.questions.put("abc","123");
    ......// more code //// ...
    }Kind regards,I was trying to steer him toward the solution himself, rather than just spoon-feed him

  • Hashtable locking question

    I see that the put and get methods of Hashtable are synchronized, which is great for multi-thread execution, however, if outside the Hashtable class I use
    Hashtable t = new Hashtable();
    synchronized(t) {
       // loop over the hashtable in here and print out the values
    }is that synchronized block using the same lock as Hashtable's internal one? In other words, if I'm inside that synchronized block am I assured that no other thread can call get() or put()?
    I'm just looking for the proper way to iterate over the Hashtable while assuring myself it won't be modified.
    thanks!!!

    I looked up the SynchronizedMap source and don't see a big difference between it and Hashtable. SM uses synchronized blocks in every function and Hashtable uses synchronized methods. Is their a difference? If it's just a matter of one way being preferred over another let me know.
    Also, I'd still like an answer to my original question about the locks...is the object lock in a synchronized block the same as the class lock on that object's synchronized methods (see my example in post 1)?
    thanks!

  • Hashtable keys( ) question

    Hello guys,
    I have a question regarding hashtables.
    Here is a method which returns a vector that contains some items:
    public Vector getVectorItems()
            Vector oVector  = new Vector();
            Enumeration oEnum = coQueue.keys();
            while (oEnum.hasMoreElements())
                    oVector.add((String)oEnum.nextElement());
            return oVector;
    }My Question:
    There are times that when oVector is returned, it is empty.
    Up to now, I'm still wondering why is the vector was empty.
    Thank you very much for your help.

    You can use an Iterator instead ...
    public Vector getVectorItems() {
    Vector oVector = new Vector();
    Iterator iter = ((Set)coQueue.keySet()).iterator();
    while (iter.hasNext()) {
    oVector.add((String)iter.next());
    return oVector;
    Also, assuming coQueue is a HashMap, use the function KeySet() instead of keys().
    try it ....

  • Hashtable not updated, question for experts!

    I have a Hashtahble which holds a pait <key, MyObject>, the I get the object via the get Method provided by the hastable class as follows:
    MyObject obj=(MyObject)myHashTable.get(key);
    then i modify the properties of my object:
    obj.updateProperties();
    and I have a thread that prints the properties of my object, so I get it in the same way via the GET method, but when I print the properties, they have not been updated.
    MyObject obj=(MyObject)myHashTable.get(key);
    obj.printProperties();
    If I debug it I cans see how the value of the properties are updated within the "updateProperties" method in the class MyObject.
    Anybody knows if when I use GET from the hashtable classe it returns a reference or a new instance of an object stored in the hashtable?
    Many thanks in advance.

    I solve the problem it was a mistake in my source code.
    ------------(SOLVED)---------------

  • Hashtable mapping question

    Hello All:
    I have a hashtable object in my java code thats represented as a jobject in my jni code. I then call GetObjectClass to get the class for this jobject. Finally I call GetMethodID to retrieve the method ID for the put method of the hashtable. At this last step I keep getting an exception access violation, I was wondering what I may be missing here. The code is shown below
    Note that decoderInfoHash is a jobject passed into my native method
    jclass hashClass=(*env)->GetObjectClass(env,decoderInfoHash);
    jmethodID putMethod = (*env)->GetMethodID(env,hashClass,"put","Ljava/lang/Object;,Ljava/lang/Object;,Ljava/lang/Object;");
    Note that the put method takes two objects and returns an object as specified above
    Is my signature correct for the GetMethodID and also can I even use GetMethodID to do this, The code currently throws a exception access violation on the GetMethodID call
    Any help would be appreciated

    Hi,
    Nope, that signature is wrong. It should look like
    "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"
    You might want to check out Jace, http://jace.reyelts.com/jace. It can generate C++ proxy classes for any Java classes, so you don't have to worry about things like getting your type signatures correct.
    God bless,
    -Toby Reyelts

  • (quick question)adding key value pairs to hashtable

    I know I can create a hashtable and add key value pairs to it with
    Hashtable numbers = new Hashtable();
    numbers.put("one", new Integer(1));
    numbers.put("two", new Integer(2));
    numbers.put("three", new Integer(3));
    But this is somewhat annoying when I want to add alot of elements. Is there a way to add the elements when I initialize the table. Perhaps something like
    Hashtable numbers =
    new HashTable("one",new Integer(1),"two",new Integer(2) )

    If you don't see such a ctor in the javadocs, then there's no easy way to do it.
    You'll just have to create two Collections of key, value pairs and add them in programmatically yourself:
    import java.util.*;
    public class MapLoader
        public static void main(String [] args)
            if ((args.length > 0) && (args.length % 2 == 0))
                List keys = new ArrayList();
                List values = new ArrayList();
                for (int i = 0; i < args.length; )
                    keys.add(args[i++]);
                    values.add(args[i++]);
                MapLoader mapLoader = new MapLoader();
                System.out.println(mapLoader.loadMap(keys, values));
        public Map loadMap(final Collection keys, final Collection values)
            if (keys.size() != values.size())
                throw new IllegalArgumentException("Must have a key for every value and visa versa");
            Map result = new HashMap(keys.size());
            Iterator keysIter = keys.iterator();
            Iterator valuesIter = values.iterator();
            while (keysIter.hasNext() && valuesIter.hasNext())
                result.put(keysIter.next(), valuesIter.next());
            return result;
    }MOD

  • How can I get the total "values" in a hashtable ?

    i know that i can get the total values in a hashtable by hash.elements() method. It returns an
    enumeration with all the values present in this hashtable. this is fine upto here.
    Now the preoblem is:
    According to what rule this enumeration will be returned. I mean..
    If i added in key A with value a,
    then key B with value b;
    then key C with value c;
    then key D with value d;
    (They all are objects of type String)
    now i call ... hash.elements(); Suppose it returns Enumeration enum;.
    Now in what order they all are present in this hashtable.
    Meaning is that if i move arond this enum in what sequence they all will be returned.
    option A ) In the same order as they were inserted in hashtable.
    option B ) According to LIFO;
    option C) There is no fix rules , simply it return all the elements and u cannot judge that the first element in enum was really the first element inserted in the hashtable and the second element of enum was really the second element inserted in the hashtable.
    What do u think..which option is correct ?
    Ny idea will highly appreciated.
    Thanks in advance.
    Sanjeev Dhiman

    hi, i am again..
    boss ! this is not true..u just change the order and or change the keys and something like ...
    "Sanjeev", "hello"
    "Dhiman", "hi"
    "Technosys" ,"Services"
    u will find that its not LIFO..really i was thinking before coding my project that option A is correct and with knowledge i wrote 3 - 4 classes but when i run the programm its starts throwing errors.
    so, i posted this question. I think "apppu" is right.
    I think , firstly hash is calculated for each value and that value is returned which can be received in a fastest way and hence not necessarily in LIFO and FIFO..
    Thanks to u also as u gave ur precious time for me.
    Once again.
    Thank you very much.
    Sanjeev Dhiman

  • Stateless Session Bean + EJB Question + Jboss

    Hello,
    If I have a stateless session bean on a linux machine and it works locally what do i need to do to access a method in the session bean from a remote windows machine.
    I would like to be able to execute my client jar file on a windows machine and have it access the jboss server on the linux machine. what do i need to do?
    i have the session bean working locally on both windows and linux machine. do i need to to have a JSP/Servlet to access the session bean? can the session bean not be accessed directly? what should my classpath look like? do I need to include extra jar files in my client jar file.?
    Thanks,
    Joyce

    Thanks guys for the help but I am still a little lost.
    My Client windows machine has the client jar file and all the other jar files. This is my client class
    package helloworld.client;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import java.util.Hashtable;
    import java.util.Properties;
    import helloworld.interfaces.HelloWorldHome;
    import helloworld.interfaces.HelloWorld;
    public class HelloClient
         public static void main(String[] args)
              Hashtable prop = new Hashtable();
              prop.put ("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
              prop.put ("java.naming.provider.url","jnp://172.16.220.160:1099");
              prop.put ("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
              try
                   Context ctx = new InitialContext(prop);
                   Object obj = ctx.lookup("ejb/helloworld/HelloWorld");
                   System.out.println(obj);
                   HelloWorldHome home = (HelloWorldHome)javax.rmi.PortableRemoteObject.narrow(obj, HelloWorldHome.class);
                   HelloWorld helloWorld = home.create();
                   String str = helloWorld.sayHelloEJB("JOYCE is COOL");
                   System.out.println(str);
                   helloWorld.remove();
              catch(Exception e)
                   e.printStackTrace();
    I get a NullPointer ie the home object is null. The IP address is the IP of the Linux machine that has Jboss running on.
    Questions are:
    1. Do I need to have Tomcat running on my client machine if I am to connect via HTTP? Does this alter my client code.?
    2. My JNDI lookup is what is causing the problem. Does my jboss.xml and my ejb-jar.jar look okay to you.
    jboss.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS//EN" "http://www.jboss.org/j2ee/dtd/jboss.dtd">
    <jboss>
    <enterprise-beans>
    <session>
    <ejb-name>helloworld/HelloWorld</ejb-name>
    <jndi-name>ejb/helloworld/HelloWorld</jndi-name>
    </session>
    </enterprise-beans>
    <resource-managers>
    </resource-managers>
    </jboss>
    ejb-jar.jar
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
    <ejb-jar >
    <description>No Description.</description>
    <display-name>Generated by XDoclet</display-name>
    <enterprise-beans>
    <!-- Session Beans -->
    <session >
    <description><![CDATA[No Description.]]></description>
    <ejb-name>helloworld/HelloWorld</ejb-name>
    <home>helloworld.interfaces.HelloWorldHome</home>
    <remote>helloworld.interfaces.HelloWorld</remote>
    <ejb-class>helloworld.session.HelloWorldBean</ejb-class>
    <session-type>Stateless</session-type>
    <transaction-type>Bean</transaction-type>
    </session>
    <!--
    To add session beans that you have deployment descriptor info for, add
    a file to your merge directory called session-beans.xml that contains
    the <session></session> markup for those beans.
    -->
    <!-- Entity Beans -->
    <!--
    To add entity beans that you have deployment descriptor info for, add
    a file to your merge directory called entity-beans.xml that contains
    the <entity></entity> markup for those beans.
    -->
    <!-- Message Driven Beans -->
    <!--
    To add message driven beans that you have deployment descriptor info for, add
    a file to your merge directory called message-driven-beans.xml that contains
    the <message-driven></message-driven> markup for those beans.
    -->
    </enterprise-beans>
    <!-- Relationships -->
    <!-- Assembly Descriptor -->
    <assembly-descriptor >
    <!-- finder permissions -->
    <!-- transactions -->
    <!-- finder transactions -->
    </assembly-descriptor>
    </ejb-jar>
    Do I need RMI ? Do I need to concern myself with CORBA? All Im looking for is a step by step to understanding what I need to configure? Is their some way I can debug?
    Thanks alot,
    Joyce

  • A question about concurrency and static getter methods

    Hello
    I have a class with some static methods. they just return a reference and doesnt apply any changes.
    something like this:
    public class FieldMapper {
            private static Map<Class,Map<String,String>> fieldMap = new HashMap<Class,Map<String,String>>();
            public static getFields(Class clazz){
                  return fieldMap.get(clazz);
    }my question is, let's consider many users connect to my server and each has its own session, now assume one user want to use FieldMapper.getFields(User.class) and another is going to call FieldMapper.getFields(Employee.class) at same time or a bit milli seconds after, and this method is not synchronized, is there any conflict in calling the method? would this method return wrong reference to the first invocation?
    in genereal, may the concurrency make problem on reading resources? or just on changing resources?
    Thank you very much in advance.

    To publish an object safely, both the reference to the object and the object's state must be made visible to other threads at the same time. A properly constructed object can be safely published by:
    Initializing an object reference from a static initializer;
    Storing a reference to it into a volatile field or AtomicReference;
    Storing a reference to it into a final field of a properly constructed object; or
    Storing a reference to it into a field that is properly guarded by a lock. The internal synchronization in thread-safe collections means that placing an object in a thread-safe collection, such as a Vector or synchronizedList, fulfills the last of these requirements. If thread A places object X in a thread-safe collection and thread B subsequently retrieves it, B is guaranteed to see the state of X as A left it, even though the application code that hands X off in this manner has no explicit synchronization.
    Now in the case you have specified you are using HashMap. Which is not designed to be threadsafe as opposed to HashTable or concurrentHashMap. In such a case I would advise against using this. The concurrency problem is caused by race conditions on mutable objects, whether it is reading or writing. If it is mutable, it is susceptible to race conditions. IMHO
    &spades;

  • Can anyone explain this to me, please. It's a static section question.

    Can anyone explain this to me, please. It's a static section question.
    I came across the following style of programming recently and I would like to know what the Static section is actually doing in the class. Thx.
    Here is the code.
    public class ClassA {
         private static Hashtable ClassAList = new Hashtable();
         private ClassB cB;
         private Vector goodLink;
         private Hashtable classCList;
         static
              ClassA cA = new ClassA();
              ClassAList.put("whatever", cA);
         public static ClassA getClassA()
              return (ClassA) ClassAList.get("whatever");

    hi,
    The static section shall be loaded before it's constructor is called. (i.e at the time of loading the class). Therefore making it available for any other objects to call.
    hope this clarifies ur question
    prasanna

Maybe you are looking for

  • LCD screen iMac

    Sorry if posting this topic here offends anyone but I was at a bit of a loss just where to post this query. It relates to cleaning the frequent smudges I seem to accumulate on my LCD screen. I checked at my local Apple shop who wanted me to pay an ex

  • Best laptop for ADF development?

    Hi all, The next week I want to buy a new laptop for adf development and the question is What are the optimal requirements to run jdev and deploy big apps to the integrated weblogic without lost my hair. I know this is a well commented issue in this

  • Excise stock registers initiallization procedure after stock upload

    Dear Gurus, I am currently facing a SAP Excise Duty issue when trying to get in the "actual closing stock" column of the inventory settlement report (TCODE /BEV2/EDIS) the quantity of stock contained within material documents generated during stock i

  • Needs help regarding block corruption

    DB Version - 11.2.0.3.0 Issue - Last backup failed due to block corruption ,message says "ORA-19566: exceeded limit of 0 corrupt blocks for file /GP/GAA01-N-P/db00/index01/GPEDWPR/bi_gpedw_fcct.dbf' I tried to perform block recovery using RMAN but it

  • Variable  0CYMONTH

    Hello, the standard variable 0CYMONTH ( characteristic "Calendar Year/Month" ) is setted as "authorization" process. Do you know how is it filled ? We didn't create any role with this variable. Thanks, Laura