Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a Java Expert!

Join 244,296 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 860 people online right now. Registration is fast and FREE... Join Now!




Accessing a hashtable in another class

 
Reply to this topicStart new topic

Accessing a hashtable in another class

simonc
1 Dec, 2008 - 11:48 AM
Post #1

D.I.C Head
**

Joined: 17 Nov, 2008
Posts: 55

Hi, very very very new to java and need some help..
I have created a Hashtable in a class called Timeseries, and I would like to access these Hashtables in Another class called DataManipulation. But everything I try doesn't work. Could some one have a look at the code below and let me know how to do it please. I have taken out some code to make the listing more manageable.

Very many thanks
Simon

java

package StatPairsModel;

public class TimeSeriesManiputaion {


void addIdTogether(int start,int finish){
int Total=0;
for(int i = start; i<finish;i++){

//**I would like to access the getid hashtable from Timeseries here so I can do stuff with the data here
//but i get the error ' The method getId(Hashtable) in the type Timeseries is not applicable for the arguments (String)'
String newString = "1234" + i;
Total=Total+Timeseries.getId(newString);
}
}
}


java

package StatPairsModel;

import java.util.Hashtable;

public class Timeseries{

Hashtable mnemonicMap = new Hashtable();
Hashtable idMap = new Hashtable();


public void setTimeseries(Hashtable mnemonicMapln,Hashtable idMapln) {

mnemonicMap = mnemonicMapln;
idMap = idMapln;

}

public void setMnemonic(Hashtable mnemonicMapln) {
mnemonicMap = mnemonicMapln;
}

public Hashtable getMnemonic(Hashtable mnemonicMap) {
return mnemonicMap;
}

public void setIdMap(Hashtable idMapln) {
idMap = idMapln;
}

public Hashtable getId(Hashtable idMap) {
return idMap;
}


void displayTsRecord(String keyField){
System.out.println();
System.out.println("mnemonic: "+Timeseries.this.mnemonicMap.get(keyField));
System.out.println("id: "+Timeseries.this.idMap.get(keyField));

}


void displayTsData() {
System.out.print(Timeseries.this.mnemonicMap + "\t");
System.out.print(Timeseries.this.idMap + "\t");
}


}



java
	
package StatPairsModel;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Enumeration;

public class DataAccess {

String address;
int dataPointCount = 0;
int dayCounter = 0;

DataAccess(String address) {

int requiredPriceFrom = 0;
int totalPricesRequired = 100;
String tempDateField = "";
String tempField = "";
String thisLine;
// timeseries
Hashtable mnemonicMap = new Hashtable();
Hashtable idMap = new Hashtable();

{
try {

FileReader file = new FileReader(address);
BufferedReader buff = new BufferedReader(file);
String keyField = null;

boolean eof = false;
dataPointCount = 0;
dayCounter = 0;
while ((thisLine = buff.readLine()) != null && !eof) {
StringTokenizer st = new StringTokenizer(thisLine, ",");

while (st.hasMoreElements()) {

if (address == "c:....txt") {

for (int i = 0; i < 2; i++) {

String field = st.nextToken();
switch (i) {
case 0:
keyField = field + dayCounter;
System.out.print(keyField + "\t");
mnemonicMap
.put(keyField, new String(field));
System.out.print(mnemonicMap.get(keyField)
+ "\t");
break;
case 1:
tempField = field;
idMap.put(keyField, new String(field));
System.out
.print(idMap.get(keyField) + "\t");
break;

}
dataPointCount++;
}
dayCounter++;


}
}


}else{
System.out
.println("File address "
+ address
+ " not correct, "
+ "please make sure file paths are present and correct");

}
}


}

}
System.out.println();


}


} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}

}

Timeseries myTimeseries = new Timeseries();

myTimeseries.setTimeseries(mnemonicMap, idMap, dateMap,
close_price_euroMap, close_volumeMap, close_mcapMap,
close_corp_actionMap, betaMap, close_price_localMap);

myTimeseries.displayTsRecord("1234560");

}

void process() {
System.out.println("Processing....");
}
}

*edit: Please use code tags in the future, thanks! code.gif

This post has been edited by Martyr2: 1 Dec, 2008 - 11:58 AM

User is offlineProfile CardPM
+Quote Post


Martyr2
RE: Accessing A Hashtable In Another Class
1 Dec, 2008 - 12:08 PM
Post #2

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 6,656



Thanked: 613 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Well right now the hash tables are private to your timeseries class and so you have two choices. Make them public by putting "public" on the front of their definitions and then you can access them directly through an instance of your timeseries class...

java

Timeseries t = new TimeSeries();
t.idMap.put("blahkey","blahvalue");


Or the better alternative is to only interact with your hash tables through public methods of the class. You have already begun doing this using methods like setIdMap() and getId() but instead of just returning or setting the whole hash table you would make a method like...

java

Timeseries t = new TimeSeries();
t.addToIdMap("blahkey","blahvalue");


... and then in the addToIdMap() method you would take in the parameters, evaluate them to make sure they are correct and then put them into the hash table directly because your methods of the class Timeseries can see, and access, the private hash tables you defined in that class.

Hope I am making a bit of sense to you here. You can find more information on what I am talking about by looking up the keyword "encapsulation" and "creating a public interface for your class".

Enjoy! smile.gif

"At DIC we create public interfaces all the time... but if you were to look at us directly, our interface would probably scare you." decap.gif
User is offlineProfile CardPM
+Quote Post

simonc
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 05:56 AM
Post #3

D.I.C Head
**

Joined: 17 Nov, 2008
Posts: 55

QUOTE(Martyr2 @ 1 Dec, 2008 - 12:08 PM) *

Well right now the hash tables are private to your timeseries class and so you have two choices. Make them public by putting "public" on the front of their definitions and then you can access them directly through an instance of your timeseries class...

java

Timeseries t = new TimeSeries();
t.idMap.put("blahkey","blahvalue");


Or the better alternative is to only interact with your hash tables through public methods of the class. You have already begun doing this using methods like setIdMap() and getId() but instead of just returning or setting the whole hash table you would make a method like...

java

Timeseries t = new TimeSeries();
t.addToIdMap("blahkey","blahvalue");


... and then in the addToIdMap() method you would take in the parameters, evaluate them to make sure they are correct and then put them into the hash table directly because your methods of the class Timeseries can see, and access, the private hash tables you defined in that class.

Hope I am making a bit of sense to you here. You can find more information on what I am talking about by looking up the keyword "encapsulation" and "creating a public interface for your class".

Enjoy! smile.gif

"At DIC we create public interfaces all the time... but if you were to look at us directly, our interface would probably scare you." decap.gif



Thanks for the reply. I'm really new to all this and am not sure how to make my hash table public (in order to access in another class), or how to finish writing a public method to interact with the class (or how to structure the call statement). I've been wrestling with this for days and can't get my head round it. Could you help by providing an example of how I do the above please.

As ever very many thanks
Simon

User is offlineProfile CardPM
+Quote Post

KYA
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 06:27 AM
Post #4

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 9,508



Thanked: 363 times
Dream Kudos: 2550
Expert In: C, C++, Java

My Contributions
java

public class A
{
private varYouNeedToAccess;

//constructor
//methods
public getVarYouneedToAccess()
{
return varYouNeedToAccess;
}
}


public class B
{
//B's stuff
}


//in a main somewhere
//A is declared
//B is declared
B.objectSomethings = A.getVaryouNeedToAccess();
//so on and so forth

User is offlineProfile CardPM
+Quote Post

simonc
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 11:10 AM
Post #5

D.I.C Head
**

Joined: 17 Nov, 2008
Posts: 55

QUOTE(KYA @ 4 Dec, 2008 - 06:27 AM) *

java

public class A
{
private varYouNeedToAccess;

//constructor
//methods
public getVarYouneedToAccess()
{
return varYouNeedToAccess;
}
}


public class B
{
//B's stuff
}


//in a main somewhere
//A is declared
//B is declared
B.objectSomethings = A.getVaryouNeedToAccess();
//so on and so forth



User is offlineProfile CardPM
+Quote Post

simonc
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 11:19 AM
Post #6

D.I.C Head
**

Joined: 17 Nov, 2008
Posts: 55


Thanks for the reply, It may sound funny, but I'm still confused.
This is how I have interpreted the last post:
I create and set a few hashtables in the Timeseries class
and try to query one of these tables via the Engine class, but it only returns a null
I'm really struggling (I have a few books but no support or way of learning (that I can afford) other than you guys so any help is really deeply appreciated
Thanks Simon

CODE


import java.io.IOException;
import java.util.Hashtable;

public class Engine {

    public static void main(String[] arguments) {

        DataAccess tsData = new DataAccess("c:...");
        
//**the next line outputs a null(the record does exist)
         System.out.println(myTimeseries.getSingleId("1234561"));
        
    }

}



CODE



package StatPairsModel;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Enumeration;

public class DataAccess {

    String address;
    int dataPointCount = 0;
    int dayCounter = 0;

    DataAccess(String address) {

        int requiredPriceFrom = 0;
        int totalPricesRequired = 100;
        String tempDateField = "";
        String tempField = "";
        String thisLine;
        // timeseries
        
        
        if (address == "c:...") {
        
        Hashtable mnemonicMap = new Hashtable();
        Hashtable idMap = new Hashtable();
        Hashtable dateMap = new Hashtable();
        
        
        {
            try {

                FileReader file = new FileReader(address);
                BufferedReader buff = new BufferedReader(file);
                String keyField = null;

                boolean eof = false;
                dataPointCount = 0;
                dayCounter = 0;
                
                
                if (address == "c:...") {
                    
                    
                while ((thisLine = buff.readLine()) != null && !eof) {
                    StringTokenizer st = new StringTokenizer(thisLine, ",");

                    while (st.hasMoreElements()) {

                        

                            for (int i = 0; i < 4; i++) {

                                String field = st.nextToken();
                                switch (i) {
                                case 0:
                                    keyField = field + dayCounter;
                                    System.out.print(keyField + "\t");
                                    mnemonicMap
                                            .put(keyField, new String(field));
                                    System.out.print(mnemonicMap.get(keyField)
                                            + "\t");
                                    break;
                                case 1:
                                    tempField = field;
                                    idMap.put(keyField, new String(field));
                                    System.out
                                            .print(idMap.get(keyField) + "\t");
                                    break;
                                case 2:
                                    tempField = field;
                                    dateMap.put(keyField, new String(field));
                                    System.out.print(dateMap.get(keyField)
                                            + "\t");
                                    break;
                                
                                }
                                dataPointCount++;
                            }
                            dayCounter++;
                        
                                        
                                
                            }else{
                                System.out
                                .println("File address "
                                        + address
                                        + " not correct, "
                                        + "please make sure file paths are present and correct");

                            }
                            }
                            
                                                    
                        }



                
            } catch (IOException e) {
                System.out.println("Error -- " + e.toString());
            }

        }

        Timeseries myTimeseries = new Timeseries();

        myTimeseries.setTimeseries(mnemonicMap, idMap, dateMap,
                close_price_euroMap, close_volumeMap, close_mcapMap,
                close_corp_actionMap, betaMap, close_price_localMap);

        myTimeseries.displayTsRecord("1234560");
        myTimeseries.getSingleId("1234560");

    }}

    }
}




CODE


package StatPairsModel;

import java.util.Hashtable;

public class Timeseries{

    Hashtable mnemonicMap = new Hashtable();
    Hashtable idMap = new Hashtable();
    Hashtable dateMap = new Hashtable();

    String singleId;
    public void setTimeseries(Hashtable mnemonicMapln,Hashtable idMapln,Hashtable dateMapln,Hashtable close_price_euroMapln,
            Hashtable close_volumeMapln,Hashtable close_mcapMapln,Hashtable close_corp_actionMapln,
            Hashtable betaMapln,Hashtable close_price_localMapln) {
        
        mnemonicMap = mnemonicMapln;
        idMap = idMapln;
        dateMap = dateMapln;

    }

    public void setMnemonic(Hashtable mnemonicMapln) {
        mnemonicMap = mnemonicMapln;
    }

    public Hashtable getMnemonic(Hashtable mnemonicMap) {
        return mnemonicMap;
    }

    public void setIdMap(Hashtable idMapln) {
        idMap = idMapln;
    }

    public Hashtable getId(Hashtable idMap) {
        return idMap;
    }

    public void setDate(Hashtable dateMapln) {
        dateMap = dateMapln;
    }

    public Hashtable getDate(Hashtable dateMap) {
        return dateMap;
    }

//**this is where I try to extract the data from the hashtable
    public String getSingleId(String keyField){
        
        Timeseries.this.idMap.get(keyField);
        return singleId;
    }

    }
    




User is offlineProfile CardPM
+Quote Post

Martyr2
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 11:39 AM
Post #7

Programming Theoretician
Group Icon

Joined: 18 Apr, 2007
Posts: 6,656



Thanked: 613 times
Expert In: C/C++, Java, VB, VB.NET, C#, PHP, Web Development, HTML & CSS, Javascript

My Contributions
Closer...

java

//**this is where I try to extract the data from the hashtable
public String getSingleId(String keyField){

Timeseries.this.idMap.get(keyField);
return singleId;
}


// Actual way

public String getSingleId(String keyField) {

// If key is found, cast it to string and return
// Otherwise return empty string.
if (idMap.get(keyField) != null) {
return (String) idMap.get(keyField);
}
return "";
}


So give that a try. If it says something about an improper cast, try using .toString on the get(). But notice how we can use the idMap directly as if it was defined in the function. This is because the method belongs to the class where the hashmap was defined. Methods of a class can see the class' member variables.

smile.gif
User is offlineProfile CardPM
+Quote Post

simonc
RE: Accessing A Hashtable In Another Class
4 Dec, 2008 - 01:00 PM
Post #8

D.I.C Head
**

Joined: 17 Nov, 2008
Posts: 55

Thanks for your help, I can now pull data out of a hashtable when i put the query in the DataAccess class, but the last bit I would like to know is how do I access the hashtable from another class? I can extract the data from the Hashtable when I have the get statement in the DataAccess class, but I would like to do any data manipulation that I have to do in a class called Engine. Below is an attempt to get the Engine class to do this but I cannot not get the code to work i get cannot be resolved errors for the following line.

System.out.println(myTimeseries.getSingleId("1234561"));

please see below for code:

Thanks so much for all your help

CODE

package StatPairsModel;

import java.io.IOException;
import java.util.Hashtable;

public class Engine {

    public static void main(String[] arguments) {

        DataAccess tsData = new DataAccess("c:...");
        
//**the following line has the cannot be resolved error, not sure what to do here
        
         System.out.println(myTimeseries.getSingleId("1234561"));
        
    }
}


CODE


package StatPairsModel;

import java.util.Hashtable;

public class Timeseries {

    Hashtable mnemonicMap = new Hashtable();
    Hashtable idMap = new Hashtable();
    Hashtable dateMap = new Hashtable();
    
    public void setTimeseries(Hashtable mnemonicMapln, Hashtable idMapln,
            Hashtable dateMapln, ) {

        mnemonicMap = mnemonicMapln;
        idMap = idMapln;
        dateMap = dateMapln;
        }    }

    public void setMnemonic(Hashtable mnemonicMapln) {
        mnemonicMap = mnemonicMapln;
    }

    public Hashtable getMnemonic(Hashtable mnemonicMap) {
        return mnemonicMap;
    }

    public void setIdMap(Hashtable idMapln) {
        idMap = idMapln;
    }

    public Hashtable getId(Hashtable idMap) {
        return idMap;
    }

    public void setDate(Hashtable dateMapln) {
        dateMap = dateMapln;
    }

    public Hashtable getDate(Hashtable dateMap) {
        return dateMap;
    }
    
    public String getSingleId(String keyField) {

        if (idMap.get(keyField) != null) {
            return (String) idMap.get(keyField);
        }
        return "";
    }
}


CODE

package StatPairsModel;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Vector;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Enumeration;

public class DataAccess {

    String address;
    int dataPointCount = 0;
    int dayCounter = 0;

    DataAccess(String address) {

        int requiredPriceFrom = 0;
        int totalPricesRequired = 100;
        String tempDateField = "";
        String tempField = "";
        String thisLine;
            
        if (address == "c:......") {
        
        Hashtable mnemonicMap = new Hashtable();
        Hashtable idMap = new Hashtable();
        Hashtable dateMap = new Hashtable();
                
        {
            try {

                FileReader file = new FileReader(address);
                BufferedReader buff = new BufferedReader(file);
                String keyField = null;

                boolean eof = false;
                dataPointCount = 0;
                dayCounter = 0;
                
                
                if (address == "c:....") {
                    
                    
                while ((thisLine = buff.readLine()) != null && !eof) {
                    StringTokenizer st = new StringTokenizer(thisLine, ",");

                    while (st.hasMoreElements()) {
                            for (int i = 0; i < 4; i++) {

                                String field = st.nextToken();
                                switch (i) {
                                case 0:
                                    keyField = field + dayCounter;
                                    System.out.print(keyField + "\t");
                                    mnemonicMap
                                            .put(keyField, new String(field));
                                    System.out.print(mnemonicMap.get(keyField)
                                            + "\t");
                                    break;
                                case 1:
                                    tempField = field;
                                    idMap.put(keyField, new String(field));
                                    System.out
                                            .print(idMap.get(keyField) + "\t");
                                    break;
                                case 2:
                                    tempField = field;
                                    dateMap.put(keyField, new String(field));
                                    System.out.print(dateMap.get(keyField)
                                            + "\t");
                                    break;
                                                                }
                                dataPointCount++;
                            }
                            dayCounter++;
                                                        
                            }else{
                                System.out
                                .println("File address "
                                        + address
                                        + " not correct, "
                                        + "please make sure file paths are present and correct");

                            }
                            }
    
                        }

                
                    System.out.println();

            } catch (IOException e) {
                System.out.println("Error -- " + e.toString());
            }

        }

        Timeseries myTimeseries = new Timeseries();

        myTimeseries.setTimeseries(mnemonicMap, idMap, dateMap,
                close_price_euroMap, close_volumeMap, close_mcapMap,
                close_corp_actionMap, betaMap, close_price_localMap);

        //**The call to the Hashtable works here, but not in the engine class
        System.out.println(myTimeseries.getSingleId("1234560"));
        

    }}

    void process() {
        System.out.println("Processing....");
    }
}

User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 7/4/09 04:43PM

Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month