Hash Table Extract
Hi,
I'm hoping that someone will be able to explain how I extract the first element (in this case the name) from the hashtable in the server code below (case N:).
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
private PrintWriter pw;
private BufferedReader bf;
private ServerSocket ss;
private Socket s;
//Hashtable used to store test data
//Set up hash table with test data
private Hashtable emails;
public Server() throws Exception{
emails = new Hashtable();
emails.put("Ince","[email protected]");
emails.put("Roberts","[email protected]");
emails.put("Timms","[email protected]");
emails.put("Rowlands","[email protected]");
emails.put("Eustace","[email protected]");
emails.put("Lord","[email protected]");
System.out.println("...Setting up server socket");
ss = new ServerSocket(1200);
System.out.println("..waiting for connection ");
s = ss.accept();
System.out.println("..connection made");
InputStream is = s.getInputStream();
bf = new BufferedReader(new InputStreamReader(is));
OutputStream os = s.getOutputStream();
pw = new PrintWriter(os, true);
public void Run() throws Exception
boolean cont = true;
while(cont == true)//server runs while true
String clientLine = bf.readLine();
System.out.println( clientLine ); //used to check the connection
switch(clientLine.charAt(0))
case'E':
String Name = "";
String staffName = null;
Name = clientLine.substring(1,clientLine.length());
staffName = (String) emails.get(Name);
pw.println(staffName);
break;
case'N':
String email = "";
String emailAddress = null;
email = clientLine.substring(1,clientLine.length());
emailAddress = (String) emails.get(email);
pw.println(emailAddress);
break;
case'U':
String number = (String) emails.get(clientLine);
if(number == null)
pw.println(number);
break;
case'Q':
pw.close();
bf.close();
s.close();
cont = false;
break;
public static void main(String[]args) throws Exception{
Server serv = new Server();
serv.Run();
}
1) Use HashMap if possible, rather than Hashtable.
2) HashMap and Hashtable don't have a "first" element. You can call entrySet(), keySet(), or values() and get the first element from the resulting collection's iteration, but that could be any element from the map--first added, last added, middle. It has no relation to the order added or to any sorting.
If you want to retrieve in the order added, use LinkeHashMap.
If you want to retrieve in a sorted order, use a SortedMap, such as TreeMap.
Make sure you implement equals and hashCode correctly, and if you want to sort, implement Comparable or provide a Comparator.
http://developer.java.sun.com/developer/Books/effectivejava/Chapter3.pdf
Making Java Objects Comparable
http://java.sun.com/docs/books/tutorial/collections/interfaces/order.html
http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-sort.html
Similar Messages
-
Question on the use of hash tables
I have created a extract program that extract data from the bkpf and the bseg tables. I am extracting a lot of data which is needed for the auditors and depending on the selection criteria (company code and date range), this extract takes quite awhile to run. I had heard from another developer working in a different project that hash tables are used when dealing with a lot of data. I am not that familiar with hash tables and was wondering if the hash table approach would help with the processing time of my process.
thanks in advance for the helpthis is only part of the code but this is the part when the selects and the writing of the file are. let me know if I have to post the entire program.
FORM f_get_data .
SELECT * INTO TABLE wt_bkpf
FROM bkpf
WHERE bukrs IN s_bukrs
AND belnr IN s_belnr
AND blart IN s_blart
AND bldat IN s_bldat
AND budat IN s_budat
AND bstat IN s_bstat.
IF sy-dbcnt IS INITIAL.
MESSAGE i208(00) WITH text-001.
STOP.
ENDIF.
SORT wt_bkpf BY bukrs belnr gjahr.
SELECT mandt bukrs belnr buzei buzid bschl koart shkzg dmbtr
wrbtr pswbt sgtxt kostl saknr hkont dmbe2
INTO TABLE wt_bseg
FROM bseg
FOR ALL ENTRIES IN wt_bkpf
WHERE bukrs EQ wt_bkpf-bukrs
AND belnr EQ wt_bkpf-belnr.
ENDFORM. " f_get_data
FORM f_split_data .
DATA wlv_index LIKE sy-tabix.
DESCRIBE TABLE wt_bkpf LINES wv_index.
wlv_index = 0.
wv_item_index = 1.
WHILE wlv_index LT wv_index.
ADD 1 TO wlv_index.
CLEAR wt_bkpf.
READ TABLE wt_bkpf INDEX wlv_index.
IF NOT sy-subrc IS INITIAL. EXIT. ENDIF.
LOOP AT wt_bseg FROM wv_item_index
WHERE bukrs EQ wt_bkpf-bukrs
AND belnr EQ wt_bkpf-belnr.
wv_item_index = sy-tabix + 1.
move wt_bkpf-bukrs to ws_bseg_hold-bukrs.
move wt_bkpf-belnr to ws_bseg_hold-belnr.
move wt_bkpf-gjahr to ws_bseg_hold-gjahr.
move wt_bkpf-blart to ws_bseg_hold-blart.
move wt_bkpf-bldat to ws_bseg_hold-bldat.
move wt_bkpf-budat to ws_bseg_hold-budat.
move wt_bkpf-monat to ws_bseg_hold-monat.
move wt_bkpf-cpudt to ws_bseg_hold-cpudt.
move wt_bkpf-cputm to ws_bseg_hold-cputm.
move wt_bkpf-usnam to ws_bseg_hold-usnam.
move wt_bkpf-tcode to ws_bseg_hold-tcode.
move wt_bkpf-xblnr to ws_bseg_hold-xblnr.
move wt_bkpf-bktxt to ws_bseg_hold-bktxt.
move wt_bkpf-waers to ws_bseg_hold-waers.
move wt_bkpf-bstat to ws_bseg_hold-bstat.
move wt_bkpf-ausbk to ws_bseg_hold-ausbk.
move wt_bseg-mandt to ws_bseg_hold-mandt.
move wt_bseg-buzei to ws_bseg_hold-buzei.
move wt_bseg-buzid to ws_bseg_hold-buzid.
move wt_bseg-bschl to ws_bseg_hold-bschl.
move wt_bseg-koart to ws_bseg_hold-koart.
move wt_bseg-shkzg to ws_bseg_hold-shkzg.
move wt_bseg-dmbtr to ws_bseg_hold-dmbtr.
move wt_bseg-wrbtr to ws_bseg_hold-wrbtr.
move wt_bseg-pswbt to ws_bseg_hold-pswbt.
move wt_bseg-sgtxt to ws_bseg_hold-sgtxt.
move wt_bseg-kostl to ws_bseg_hold-kostl.
move wt_bseg-saknr to ws_bseg_hold-saknr.
move wt_bseg-hkont to ws_bseg_hold-hkont.
move wt_bseg-dmbe2 to ws_bseg_hold-dmbe2.
APPEND ws_bseg_hold TO wt_bseg_output.
ENDLOOP.
ENDWHILE.
ENDFORM. " f_split_data -
Hi,
I have a hashtable which contains a number of objects of my custom class.
I need the properties of these objects to be stored in a jTable, a row per object.
Could anyone offer me any help,
Anything will be very much apreciatedThe title of your post is "populating a hash table" but the first sentence suggests you have already populated the hash table and you want to get data out of it.
The elements() method gives you an Enumeration that allows you to extract the values from the Hashtable.
There's a tutorial here about how to use JTables: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html -
Header, Line Item and Cache Techniques Using Hashed Tables
Hi,
How can I work with header, line item, and a cache techniques using hashed tables?
Thanks,
Shah.Hi,
Here is an example to clarify the ideas:
In general, every time you have a header-> lines structure you have a unique key for the lines that has at least header key plus one or more fields. I'll make use of this fact.
I'll try to put an example of how to work with header -> line items and a cache technique using hashed tables.
Just suppose that you need a list of all the material movements '101'-'901' for a certain range of dates in mkpf-budat. We'll extract these fields:
mkpf-budat
mkpf-mblnr,
mseg-lifnr,
lfa1-name1,
mkpf-xblnr,
mseg-zeile
mseg-charg,
mseg-matnr,
makt-maktx,
mseg-erfmg,
mseg-erfme.
I'll use two cache: one for maintaining lfa1 related data and the other to maintain makt related data. Also I'll only describe the data gathering part. The showing of the data is left to your own imagination.
The main ideas are:
1. As this is an example I won't use inner join. If properly desingned may be faster .
2. I'll use four hashed tables: ht_mkpf, ht_mseg, ht_lfa1 and ht_makt to get data into memory. Then I'll collect all the data I want to list into a fifth table ht_lst.
3. ht_mkpf should have (at least) mkpf's primary key fields : mjahr, mblnr.
4. ht_mseg should have (at least) mseg primary key fields: mjahr mblnr and zeile.
5. ht_lfa1 should have an unique key by lifnr.
6. ht_makt should have an unique key by matnr.
7. I prefer using with header line because makes the code easier to follow and understand. The waste of time isn't quite significant (in my experience at least).
Note: When I've needed to work from header to item lines then I added a counter in ht_header that maintains the count of item lines, and I added an id in the ht_lines so I can read straight by key a given item line. But this is very tricky to implement and to follow. (Nevertheless I've programmed it and it works well.)
The data will be read in this sequence:
select data from mkpf into table ht_mkpf
select data from mseg int table ht_mseg having in count all the data in ht_mkpf
loop at ht_mseg (lines)
filter unwanted records
read cache for lfa1 and makt
fill in ht_lst and collect data
endloop.
tables
tables: mkpf, mseg, lfa1, makt.
internal tables:
data: begin of wa_mkpf, "header
mblnr like mkpf-mblnr,
mjahr like mkpf-mjahr,
budat like mkpf-budat,
xblnr like mkpf-xblnr,
end of wa_mkpf.
data ht_mkpf like hashed table of wa_mkpf
with unique key mblnr mjahr
with header line.
data: begin of wa_mseg, " line items
mblnr like mseg-mblnr,
mjahr like mseg-mjahr,
zeile like mseg-zeile,
bwart like mseg-bwart,
charg like mseg-charg,
matnr like mseg-matnr,
lifnr like mseg-lifnr,
erfmg like mseg-erfmg,
erfme like mseg-erfme,
end of wa_mseg,
data ht_mseg like hashed table of wa_mseg
with unique key mblnr mjahr zeile
with header line.
data: begin of wa_lfa1,
lifnr like lfa1-lifnr,
name1 like lfa1-name1,
end of wa_lfa1,
data ht_lfa1 like hashed table of wa_lfa1
with unique key lifnr
with header line.
data: begin of wa_makt,
matnr like makt-matnr,
maktx like makt-maktx,
end of wa_makt.
data: ht_makt like hashed table of wa_makt
with unique key matnr
with header line.
result table
data: begin of wa_lst, "
budat like mkpf-budat,
mblnr like mseg-mblnr,
lifnr like mseg-lifnr,
name1 like lfa1-name1,
xblnr like mkpf-xblnr,
zeile like mseg-zeile,
charg like mseg-charg,
matnr like mseg-matnr,
maktx like makt-maktx,
erfmg like mseg-erfmg,
erfme like mseg-erfme,
mjahr like mseg-mjahr,
end of wa_mseg,
data: ht_lst like hashed table of wa_lst
with unique key mblnr mjahr zeile
with header line.
data: g_lines type i.
select-options: so_budat for mkpf-budat default sy-datum.
select-options: so_matnr for mseg-matnr.
form get_data.
select mblnr mjahr budat xblnr
into table ht_mkfp
from mkpf
where budat in so_budat.
describe table ht_mkpf lines g_lines.
if lines > 0.
select mblnr mjahr zeile bwart charg
matnr lifnr erfmg erfme
into table ht_mseg
from mseg
for all entries in ht_mkpf
where mblnr = ht_mkpf-mblnr
and mjahr = ht_mjahr.
endif.
loop at ht_mseg.
filter unwanted data
check ht_mseg-bwart = '101' or ht_mseg-bwart = '901'.
check ht_mseg-matnr in so_matnr.
read header line.
read table ht_mkpf with table key mblnr = ht_mseg-mblnr
mjahr = ht_mseg-mjahr.
clear ht_lst.
note : this may be faster if you specify field by field.
move-corresponding ht_mkpf to ht_lst.
move-corresponding ht_mseg to ht_lst.
perform read_lfa1 using ht_mseg-lifnr changing ht_lst-name1.
perform read_makt using ht_mseg-matnr changing ht_lst-maktx.
insert table ht_lst.
endloop.
implementation of cache for lfa1.
form read_lfa1 using p_lifnr changing p_name1.
read table ht_lfa1 with table key lifnr = p_lifnr
transporting name1.
if sy-subrc <> 0.
clear ht_lfa1.
ht_lfa1-lifnr = p_lifnr.
select single name1
into ht_lfa1-name1
from lfa1
where lifnr = p_lifnr.
if sy-subrc <> 0. ht_lfa1-name1 = 'n/a in lfa1'. endif.
insert table ht_lfa1.
endif.
p_name1 = ht_lfa1-name1.
endform.
implementation of cache for makt
form read_makt using p_matnr changing p_maktx.
read table ht_makt with table key matnr = p_matnr
transporting maktx.
if sy-subrc <> 0.
ht_makt-matnr = p_matnr.
select single maktx into ht_matk-maktx
from makt
where spras = sy-langu
and matnr = p_matnr.
if sy-subrc <> 0. ht_makt-maktx = 'n/a in makt'. endif.
insert table ht_makt.
endif.
p_maktx = ht_makt-maktx.
endform.
Reward points if found helpfull...
Cheers,
Siva. -
Hash Table -Runtime error.
Hi,
i am defining internal table as hash table but it is giving runtime error like bolow. some times it is executing properly or giving dump.please give me some suggestions to come out of this problem.
Ex:
What happened?
Error in the ABAP Application Program
The current ABAP program "SAPLZGIT_MED" had to be terminated because it has
come across a statement that unfortunately cannot be executed.
Error analysis
An entry was to be entered into the table
"\FUNCTION=ZBAPI_GIT_MED_HD_BOTELLAS_RPT\DATA=T_THERAPY_INFO" (which should
have
had a unique table key (UNIQUE KEY)).
However, there already existed a line with an identical key.
The insert-operation could have ocurred as a result of an INSERT- or
MOVE command, or in conjunction with a SELECT ... INTO.
The statement "INSERT INITIAL LINE ..." cannot be used to insert several
initial lines into a table with a unique key.
Code: .....................................
TYPES: BEGIN OF X_THERAPY_INFO,
GIT_THERAPY_ID TYPE ZGIT_VBELN_GIT,
CHO_THERAPY_ID TYPE VBELN,
SERVICE_ID TYPE MATNR,
SERVICE_DESC TYPE ARKTX,
FLOW TYPE ZGIT_ZFLOW,
DURATION TYPE ZGIT_ZDURATION,
GIT_PAT_ID TYPE ZGIT_KUNNR_GIT,
CHORUS_PAT_ID TYPE KUNNR,
END OF X_THERAPY_INFO,
DATA:
T_THERAPY_INFO TYPE HASHED TABLE OF X_THERAPY_INFO WITH UNIQUE KEY GIT_THERAPY_ID, " Internal table for extracting the therapy Informamtion
Extract the Therapy Details
SELECT VBELN_GIT
VBELN
MATNR
ARKTX
ZFLOW
ZDURATION
KUNNR_GIT
KUNNR
INTO TABLE T_THERAPY_INFO
FROM ZGIT_T_VBAK
WHERE KUNNR_GIT NE SPACE
AND KVGR2 IN TR_KVGR2
AND ZDOCTOR IN TR_DOC_SEL_ID
AND ZHOSPITAL IN TR_HOSPITAL_ID
AND ( ZSTATUS_ID NE C_HIDDEN
AND ZSTATUS_ID NE C_DISABLED
AND ZSTATUS_ID NE C_OTHERS )
AND VBELN IN TR_VBELN.
IF SY-SUBRC NE C_0.
Thanks in advance,
Srinivas PWhen you are using hashed tables, you cannot have duplicate records (considering it's key). So DELETE ADJACENT DUPLICATES won't solve it. It will dump before that.
Find if you are inserting records with the same fields you inserted in the key.
Example.
If your key is VBELN, you cannot make it like this:
SELECT a~vbeln b~matnr
INTO TABLE hashed_itab
FROM vbak AS a INNER JOIN vbap as b
ON a~vbeln = b~vbeln
WHERE ...
It will dump if your vbeln has 2 lines in vbap.
Two solutions:
1 - expand the itab key to VBELN and POSNR (for example) or
2
SELECT DISTINCT a~vbeln b~matnr
INTO TABLE hashed_itab
FROM vbak AS a INNER JOIN vbap as b
ON a~vbeln = b~vbeln
WHERE ...
Regards,
Valter Oliveira. -
Producing a string of 3 random letters for a hash table
I'm pretty new to all this and i was wondering if anyone would be able to help me produce a random string of 3 letters to be inputted into a hash table. I already have the code for integers to be placed into the table but am having difficulty with letters. I've tried using the Random() function but am probably putting it into the wrong place.
I will place the code underneath so you can all have a look at it.
Any help would be greatly appreciated.
Thanks in advance
Code:
class HashTable
private DataItem[] hashArray; // array holds hash table
private int arraySize;
private DataItem nonItem; // for deleted items
public HashTable(int size) // constructor
arraySize = size;
hashArray = new DataItem[arraySize];
nonItem = new DataItem(-1); // deleted item key is -1
public void displayTable()
System.out.print("Table: ");
for(int j=0; j<arraySize; j++)
if(hashArray[j] != null)
System.out.print(hashArray[j].getKey() + " ");
else
System.out.print("** ");
System.out.println("");
public int hashFunc(int key)
return key % arraySize; // hash function
public void insert(DataItem item) // insert a DataItem
// (assumes table not full)
int key = item.getKey(); // extract key
int hashVal = hashFunc(key); // hash the key
// until empty cell or -1,
while(hashArray[hashVal] != null &&
hashArray[hashVal].getKey() != -1)
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
hashArray[hashVal] = item; // insert item
} // end insert()
public DataItem delete(int key) // delete a DataItem
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{ // found the key?
if(hashArray[hashVal].getKey() == key)
DataItem temp = hashArray[hashVal]; // save item
hashArray[hashVal] = nonItem; // delete item
return temp; // return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
return null; // can't find item
} // end delete()
public DataItem find(int key) // find item with key
int hashVal = hashFunc(key); // hash the key
while(hashArray[hashVal] != null) // until empty cell,
{ // found the key?
if(hashArray[hashVal].getKey() == key)
return hashArray[hashVal]; // yes, return item
++hashVal; // go to next cell
hashVal %= arraySize; // wraparound if necessary
return null; // can't find item
} // end class HashTable
class HashTableApp
public static void main(String[] args) throws IOException
DataItem aDataItem;
int aKey, size, n, keysPerCell;
// get sizes
System.out.print("Enter size of hash table: ");
size = getInt();
System.out.print("Enter initial number of items: ");
n = getInt();
keysPerCell = 10;
// make table
HashTable theHashTable = new HashTable(size);
for(int j=0; j<n; j++) // insert data
aKey = (int)(java.lang.Math.random() *
keysPerCell * size);
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
while(true) // interact with user
System.out.print("Enter first letter of ");
System.out.print("show, insert, delete, or find: ");
char choice = getChar();
switch(choice)
case 's':
theHashTable.displayTable();
break;
case 'i':
System.out.print("Enter key value to insert: ");
aKey = getInt();
aDataItem = new DataItem(aKey);
theHashTable.insert(aDataItem);
break;
case 'd':
System.out.print("Enter key value to delete: ");
aKey = getInt();
theHashTable.delete(aKey);
break;
case 'f':
System.out.print("Enter key value to find: ");
aKey = getInt();
aDataItem = theHashTable.find(aKey);
if(aDataItem != null)
System.out.println("Found " + aKey);
else
System.out.println("Could not find " + aKey);
break;
default:
System.out.print("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class HashTableApppublic class Foo {
private java.util.Random rand = new Random();
public static void main(String[] args) throws Exception {
new Foo().go();
void go() throws Exception {
String allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(getRandomString(allowedChars, 3));
String getRandomString(String allowedChars, int length) {
StringBuffer buf = new StringBuffer();
int charCount = allowedChars.length();
for (int count = 0; count < length; count++) {
int index = rand.nextInt(charCount);
buf.append(allowedChars.charAt(index));
return buf.toString();
} -
Displaying graphical representation of data in hash tables as bar chart?
I want to be able to display results in my hash table as a bar chart i don't know how to do it could someone help me I've looked through tutorials couldn't find any information that actually helped.
In my program it doesnt allow matching the capital and small letters
so for instance if I already have Mike it allows for me to input mike in again so there are 2 Mikes.
I also want to do a simple user interface the tutorial for it is not simple to understand could any one tell me how to create a simple user interface like putting a button into a place wher i want it to be.
im not asking anyone to do it for me i just want people to show me how to do it
thank you
Edited by: Tek_Hedef on Dec 1, 2007 4:30 AMThanks for the ideas pal but I did have a go at it but my bit of code is making it crash but i removed it now so here's what I have so far
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class StudentDetails extends JFrame implements ActionListener
private JTextField StudentNameTxt, StudentMarkTxt;
private JButton DeleteStudentDetailsBtn, DisplayAllStudentsBtn, SearchStudentBtn, FailedStudentsBtn, PassedStudentsBtn, DistinctionStudentsBtn, AddStudentDetailsBtn, ExitBtn;
private JPanel DisplayStudentDetailsPnl;
private JLabel StudentNameLbl, StudentMarkLbl;
private JTextArea DisplayResultsTxt;
private Hashtable StudentDetailsTbl;
private String StudentName, StudentMark;
public static void main(String[] args)
StudentDetails frame = new StudentDetails();
frame.setSize(600,600);
frame.createGUI();
frame.setVisible(true);
public void display(JPanel DisplayStudentDetailsPnl)
Graphics paper = DisplayStudentDetailsPnl.getGraphics();
paper.setColor(Color.white);
paper.fillRect(0, 0, 500, 500);
paper.setColor(new Color((int)(Math.random()*255),(int)(Math.random()*255),(int)(Math.random()*255) ));
private void createGUI()
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
StudentDetailsTbl = new Hashtable();
StudentNameLbl = new JLabel("Student Name");
window.add(StudentNameLbl);
StudentNameTxt = new JTextField(15);
window.add(StudentNameTxt);
StudentMarkLbl = new JLabel("Student Mark");
window.add(StudentMarkLbl);
StudentMarkTxt = new JTextField(3);
window.add(StudentMarkTxt);
AddStudentDetailsBtn = new JButton("Add Student and Mark");
window.add(AddStudentDetailsBtn);
AddStudentDetailsBtn.addActionListener(this);
DeleteStudentDetailsBtn = new JButton("Delete Student");
window.add(DeleteStudentDetailsBtn);
DeleteStudentDetailsBtn.addActionListener(this);
DisplayAllStudentsBtn = new JButton("Display all Students and Marks");
window.add(DisplayAllStudentsBtn);
DisplayAllStudentsBtn.addActionListener(this);
SearchStudentBtn = new JButton("Search Student");
window.add(SearchStudentBtn);
SearchStudentBtn.addActionListener(this);
FailedStudentsBtn = new JButton("Students which Failed");
window.add(FailedStudentsBtn);
FailedStudentsBtn.addActionListener(this);
PassedStudentsBtn = new JButton("Students which Passed");
window.add(PassedStudentsBtn);
PassedStudentsBtn.addActionListener(this);
DistinctionStudentsBtn = new JButton("Students with Distinction");
window.add(DistinctionStudentsBtn);
DistinctionStudentsBtn.addActionListener(this);
ExitBtn = new JButton("Exit");
window.add(ExitBtn);
ExitBtn.addActionListener(this);
DisplayResultsTxt = new JTextArea();
DisplayResultsTxt.setPreferredSize(new Dimension(200, 200));
DisplayResultsTxt.setBackground(Color.white);
window.add(DisplayResultsTxt);
DisplayResultsTxt.enable(false);
public void actionPerformed (ActionEvent e)
if (e.getSource()== AddStudentDetailsBtn)
StudentName = StudentNameTxt.getText();
StudentMark = StudentMarkTxt.getText();
DisplayResultsTxt.setText("");
StudentDetailsTbl.put(StudentName, StudentMark);
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
String[] keys = (String[]) StudentDetailsTbl.keySet().toArray(new String[0]);
Arrays.sort(keys);
for (String key : keys)
DisplayResultsTxt.append(key + " : " + StudentDetailsTbl.get(key)+ "\n");
StudentNameTxt.setText("");
StudentMarkTxt.setText("");
if (e.getSource() == DeleteStudentDetailsBtn )
if (StudentDetailsTbl.containsKey(StudentNameTxt.getText().trim()))
DisplayResultsTxt.setText("");
String txt = StudentNameTxt.getText();
Enumeration enumStudentName = StudentDetailsTbl.keys() ;
String currentelement = (String)enumStudentName.nextElement();
StudentDetailsTbl.remove(txt);
DisplayResultsTxt.append(txt + " has been deleted");
if (e.getSource() == SearchStudentBtn)
if (StudentDetailsTbl.containsKey(StudentNameTxt.getText().trim()))
String txt = StudentNameTxt.getText();
String result;
DisplayResultsTxt.setText("");
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
while (enumStudentName.hasMoreElements())
String currentelement = (String)enumStudentName.nextElement();
result = (StudentDetailsTbl.get(currentelement).toString());
if (txt.equals(currentelement))
DisplayResultsTxt.append(currentelement + " " + result);
else JOptionPane.showMessageDialog(null, "Student Name could not be identified");
if (e.getSource() == DisplayAllStudentsBtn)
DisplayResultsTxt.setText("");
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
while (enumStudentName.hasMoreElements())
DisplayResultsTxt.append(enumStudentName.nextElement()+ " " + enumStudentMark.nextElement()+ "\n");
if (e.getSource() == PassedStudentsBtn)
DisplayResultsTxt.setText("");
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
while (enumStudentName.hasMoreElements())
int Mark = Integer.parseInt((String)enumStudentMark.nextElement());
String Name = (String)enumStudentName.nextElement();
if (Mark >=40)
DisplayResultsTxt.append(Name + " " + Mark + "\n");
if (e.getSource() == FailedStudentsBtn)
DisplayResultsTxt.setText("");
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
while (enumStudentName.hasMoreElements())
int Mark = Integer.parseInt((String)enumStudentMark.nextElement());
String Name = (String)enumStudentName.nextElement();
if (Mark <40)
DisplayResultsTxt.append(Name + " " + Mark + "\n");
if (e.getSource() == DistinctionStudentsBtn)
DisplayResultsTxt.setText("");
Enumeration enumStudentName = StudentDetailsTbl.keys();
Enumeration enumStudentMark = StudentDetailsTbl.elements();
while (enumStudentName.hasMoreElements())
int Mark = Integer.parseInt((String)enumStudentMark.nextElement());
String Name = (String)enumStudentName.nextElement();
if (Mark >=75)
DisplayResultsTxt.append(Name + " " + Mark + "\n");
} -
How about use partial key to loop at a hashed table?
Such as I want to loop a Internal table of BSID according to BKPF.
data itab_bsid type hashed table of BSID with unique key bukrs belnr gjahr buzid.
Loop at itab_bsid where bukrs = wa_bkpf-bukrs
and belnr = wa_bkpf-belnr
and gjahr = wa_bkpf-gjahr.
endloop.
I know if you use all key to access this hashed table ,it is certainly quick, and my question is when i use partial key of this internal hashed table to loop it, how about its performance.
Another question is in this case(BSID have many many record) , Sorted table and Hashed table , Which is better in performance.You can't cast b/w data reference which l_tax is and object reference which l_o_tax_code is.
osref is a generic object type and you store a reference to some object in it, right? So the question is: what kind of object you store there? Please note - this must be an object reference , not data reference .
i.e
"here goes some class
class zcl_spfli definition.
endclass.
class zcl_spfli implementation.
endclass.
"here is an OBJECT REFERENCE for it, (so I refer to a class) i.e persistent object to table SPFLI
data oref_spfli type ref to zcl_spfli.
"but here I have a DATA REFERENCE (so I refer to some data object) i.e DDIC structure SPFLI
data dref_spfli type ref to spfli.
So my OSREF can hold only oref_spfli but it not intended for dref_spfli . That's why you get this syntax error. Once you have stored reference to zcl_spfli in osref then you will be able to dereference it and access this object's attributes.
data: osref type osref.
create object osref_spfli.
osref = osref_spfli.
"now osref holds reference to object, you can deference it
oref_spfli ?= osref.
osref_spfli->some_attribute = ....
OSREFTAB is just a table whose line is of type OSREF (so can hold multiple object references - one in each line).
Regards
Marcin -
How to get values from Hash Table
Hi all,
I have a hash table "lovResults" craeted with following code -
String lovInputSourceId = pageContext.getParameter(SOURCE_PARAM);
Hashtable lovResults = pageContext.getLovResultsFromSession(lovInputSourceId);
values which I can see through SOP are - ******Value of lovResults is{roleid=1000, domainFV=CREATIVE, Role=Account Director}
How can I get the domain value "domainFV=CREATIVE" from hash table in a variable because I have to set this vaue in another field.
Please help me ASAP
Thanks
AmitHi Amit ,
Since you are successfully printing the values using sop's , please try this code
Capture the value in controller .
if(oapagecontext.getParameter("domainFV") != null)
String formvalue= oapagecontext.getParameter("domainFV") // ensure hashtable id is correct
Keerthi
Edited by: keerthioaf on Nov 26, 2012 8:46 PM -
How to use one hash table inside another hash table
Hi everyone,
Any example of hash table inside another hash table.
Can one here help me how to write one hash table inside another with repeating keys for the first hash table.
Thanks,
kanty.Do you mean you want the 'value' entries in a hash table to themselves be hash tables? Easy but this often indicates a design flaw.
Hashtable<String,<Hashtable<String,Value>> fred = new Hashtable<String,<Hashtable<String,Value>> ();But what do you mean by "with repeating keys for the first hash table"?
Edited by: sabre150 on Jul 2, 2010 10:11 PM
Looks like you have already handled the declaration side in your other thread. I suspect you should be writing your own beans that hold the information and these beans would then be stored in a Map. The problem I have is that your description is too vague so I can't be certain. -
Hello,
I am trying to just get the Managers of my users in Active Directory. I have gotten it down to the user and their manager, but I don't need the user. Here is my code so far:
Get-ADUser-filter*-searchbase"OU=REDACTED,
OU=Enterprise Users, DC=REDACTED, DC=REDACTED"-PropertiesManager|SelectName,@{N='Manager';E={(Get-ADUser$_.Manager).Name}}
|export-csvc:\managers.csv-append
Also, I need to get rid of the duplicate values in my hash table. I tried playing around with -sort unique, but couldn't find a place it would work. Any help would be awesome.
Thanks,
MattI would caution that, although it is not likely, managers can also be contact, group, or computer objects. If this is possible in your situation, use Get-ADObject in place of Get-ADUser inside the curly braces.
Also, if you only want users that have a manager assigned, you can use -LDAPFilter "(manager=*)" in the first Get-ADUser.
Finally, if you want all users that have been assigned the manager for at least one user, you can use:
Get-ADUser
-LDAPFilter "(directReports=*)" |
Select @{N='Manager';E={ (Get-ADUser
$_.sAMAccountName).Name }}
-Unique | Sort Manager |
Export-Csv .\managerList.csv -NoTypeInformation
This works because when you assign the manager attribute of a user, this assigns the user to the directReports attribute of the manager. The directReports atttribute is multi-valued (an array in essence).
Again, if managers can be groups or some other class of object (not likely), then use Get-ADObect throughout and identify by distinguishedName instead of sAMAccountName (since contacts don't have sAMAccountName).
Richard Mueller - MVP Directory Services -
Question about comparing an array of names to a hash table
I'm still learning Powershell but feel like I have the basics now. I have a new project I'm working on and want some input as the best way to do this:
The Problem:
Let's say you have a list of several hundred video game titles and the dollar value of each in a text or two column CSV file.
The example CSV file looks likes this:
Game, Price
Metroid, $15.00
The Legend of Zelda!, $12.00
Mike Tyson's Punch-Out!, $18.00
Super Mario Bros., $16.00
Kung Fu, $7.00
You have another list of just the video game titles, this most likely is just a text file with each title listed on its own line.
The example text file looks like this:
Kung Fu
Metroid
Mike Tysons Punch-Out
Legend of Zelda
What I think would happen in the Script:
Use import-csv and create a hash table that will contain a key = Title and the value = the price.
Use import-csv and create an array for the title names.
Foreach loop through each Game Title and match the value against the Hash Table, if there's a match found, put that into another array that will later add all prices of each item and give you a total sum.
The challenge:
So far when I try and do one line examples of comparing names against the hash table it seems to only work with exact name matches. In the above example I've purposely made the game titles slightly different because in the real world people just write things
differently.
With that said, I've tried using the following single line to match things up and it only seems to work if the values match exactly.
$hash_table.ContainsKey("Game Title")
Is there a regex I should use to change the input of the game titles before creating the hash table or doing the compare? Is there another matching operator that is better and matching with String values that have slightly different grammar. An example would
be the game "The Legend of Zelda". Sometimes people just put "Legend of Zelda", that's close but not exact. I think using a regex to remove extra spaces and symbols would work, but what about for matching of words or letters??
Any ideas would be very helpful and thanks!There's no pat answer for this.
You can create an array from the hash table keys:
$hashtable = @{"The Legend of Zelda" = 15.00}
$titles = $hashtable.getenumerator() | select -ExpandProperty Name
And then test that using a wildcard match:
$titles -like "*Game Title*"
and see if it returns just one match. If it does then use that match to do your lookup in the hash table. If it returns 0, or more than one match then you need to check the spelling or qualify the title search some more.
[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " " -
Hash Table Infrastructure ran out of memory Issue
I am getting ORA-32690 : Hash Table Infrastructure ran out of memory error, while executing an Informatica mapping using Oracle Database ( Test Environment)
The partition creation is as shown below.
TABLESPACE MAIN_LARGE_DATA1
PARTITION BY LIST (MKTCD)
PARTITION AAM VALUES ('AAM')
TABLESPACE MAIN_LARGE_DATA1,
PARTITION AHT VALUES ('AHT')
TABLESPACE MAIN_LARGE_DATA1,
PARTITION GIM VALUES ('GIM')
TABLESPACE MAIN_LARGE_DATA1,
PARTITION CNS VALUES ('CNS')
TABLESPACE MAIN_LARGE_DATA1,
PARTITION AOBE VALUES ('AOBE')
TABLESPACE MAIN_LARGE_DATA1,
PARTITION DBM VALUES ('DBM')
TABLESPACE MAIN_LARGE_DATA1
Could you please provide me with a solution to this problem asap?SQL statement and execution plan? Is there a server-side trace file created for the session?
From the brief description, it sounds like bug 6471770. See Metalink for details. The workaround for this particular bug is to either disable hash group-by, by setting +"_gby_hash_aggregation_enabled"+ to FALSE (using an ALTER SESSION statement . Or by using a NO_USE_HASH_AGGREGATION hint.
Suggest you research this problem on Metalink (aka MyOracleSupport at https://support.oracle.com) -
Hash tables in combination with data references to the line type.
I'm having an issue with hash tables - in combination with reference variables.
Consider the following: (Which is part of a class) - it attempts to see if a particular id exists in a table; if not add it; if yes change it.
types: BEGIN OF TY_MEASUREMENT,
perfid TYPE zgz_perf_metric_id,
rtime TYPE zgz_perf_runtime,
execount TYPE zgz_perf_execount,
last_start TYPE timestampl,
END OF TY_MEASUREMENT.
METHOD START.
DATA: ls_measurement TYPE REF TO ty_measurement.
READ TABLE gt_measurements WITH TABLE KEY perfid = i_perfid reference into ls_measurement.
if sy-subrc <> 0.
"Didn't find it.
create data ls_measurement.
ls_measurement->perfid = i_perfid.
insert ls_measurement->* into gt_measurements.
endif.
GET TIME STAMP FIELD ls_measurements-last_start.
ls_measurement->execount = ls_measurement->execount + 1.
ENDMETHOD.
I get compile errors on the insert statement - either "You cannot use explicit index operations on tables with types HASHED TABLE" or "ANY TABLE". It is possible that.
If I don't dereference the type then I get the error LS_MEASUREMENT cannot be converted to the line type of GT_MEASUREMENTS.
I'm not looking to solve this with a combination of references and work ares - want a reference solution.
Thanks!
_Ryan
Moderator message - Moved to the correct forum
Edited by: Rob Burbank on Apr 22, 2010 4:43 PMI think it might work when you change it for
insert ls_measurement->* into TABLE gt_measurements.
For hashed table a new line here will be inserted according to given table key.
Regards
Marcin -
I am trying to build a proof of concept where a WPF form is hosted in a seperate runspace and updates are handled from the primary shell/runspace. I have had some success thanks to a great article by Boe Prox, but I am having an issue I wanted to open up
to see if anyone had a suggestion.
My goals are as follows:
1.) Set control properties from the primary runspace (Completed)
2.) Get control properties from the primary runspace (Completed)
3.) Respond to WPF form events in the UI runspace from the primary runspace (Kind of broken).
I have the ability to read/write values to the form, but I am having difficulty with events. Specifically, I can fire and handle events, but the minute I try to reference the $SyncHash from within the event it appears to cause a blocking condition hanging both
runspaces. As a result, I am unable to update the form based on an event being fired by a control.
In the example below, the form is loaded and the following steps occur:
1.) Update-Combobox is called and it populates the combobox with a list of service names and selects the first item.
2.) update-textbox is called and sets the Text property of the textbox.
3.) The Text value of the textbox is read by the function read-textbox and output using write-host.
4.) An event handle is registered for the SelectionChanged event for the combobox to call the update-textbox function used earlier.
5.) If you change the selection on the combobox, the shell and UI hangs as soon as $SyncHash is referenced. I suspect this is causing some sort of blocking condition from multiple threads trying to access the synchronized nature of the hash table, but I am
unsure as to why / how to work around it. If you comment out the line "$SyncHash.TXT_Output.Dispatcher.Invoke("Send",[action]{$SyncHash.TXT_Output.Text = $Value})" within update-textbox the event handler will execute/complete.
$UI_JobScript =
try{
Function New-Form ([XML]$XAML_Form){
$XML_Node_Reader=(New-Object System.Xml.XmlNodeReader $XAML_Form)
[Windows.Markup.XamlReader]::Load($XML_Node_Reader)
try{
Add-Type –AssemblyName PresentationFramework
Add-Type –AssemblyName PresentationCore
Add-Type –AssemblyName WindowsBase
catch{
Throw "Unable to load the requisite Windows Presentation Foundation assemblies. Please verify that the .NET Framework 3.5 Service Pack 1 or later is installed on this system."
$Form = New-Form -XAML_Form $SyncHash.XAML_Form
$SyncHash.Form = $Form
$SyncHash.CMB_Services = $SyncHash.Form.FindName("CMB_Services")
$SyncHash.TXT_Output = $SyncHash.Form.FindName("TXT_Output")
$SyncHash.Form.ShowDialog() | Out-Null
$SyncHash.Error = $Error
catch{
write-host $_.Exception.Message
#End UI_JobScript
#Begin Main
add-type -AssemblyName WindowsBase
[XML]$XAML_Form = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<DataTemplate x:Key="DTMPL_Name">
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</Window.Resources>
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Label Name="LBL_Services" Content="Services:" />
<ComboBox Name="CMB_Services" ItemTemplate="{StaticResource DTMPL_Name}"/>
</StackPanel>
<TextBox Name="TXT_Output"/>
</DockPanel>
</Window>
$SyncHash = [hashtable]::Synchronized(@{})
$SyncHash.Add("XAML_Form",$XAML_Form)
$SyncHash.Add("InitialScript", $InitialScript)
$Normal = [System.Windows.Threading.DispatcherPriority]::Normal
$UI_Runspace =[RunspaceFactory]::CreateRunspace()
$UI_Runspace.ApartmentState = [System.Threading.ApartmentState]::STA
$UI_Runspace.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::ReuseThread
$UI_Runspace.Open()
$UI_Runspace.SessionStateProxy.SetVariable("SyncHash",$SyncHash)
$UI_Pipeline = [PowerShell]::Create()
$UI_Pipeline.Runspace=$UI_Runspace
$UI_Pipeline.AddScript($UI_JobScript) | out-Null
$Job = $UI_Pipeline.BeginInvoke()
$SyncHash.ServiceList = get-service | select name, status | Sort-Object -Property Name
Function Update-Combobox{
write-host "`nBegin Update-Combobox [$(get-date)]"
$SyncHash.CMB_Services.Dispatcher.Invoke($Normal,[action]{$SyncHash.CMB_Services.ItemsSource = $SyncHash.ServiceList})
$SyncHash.CMB_Services.Dispatcher.Invoke($Normal,[action]{$SyncHash.CMB_Services.SelectedIndex = 0})
write-host "`End Update-Combobox [$(get-date)]"
Function Update-Textbox([string]$Value){
write-host "`nBegin Update-Textbox [$(get-date)]"
$SyncHash.TXT_Output.Dispatcher.Invoke("Send",[action]{$SyncHash.TXT_Output.Text = $Value})
write-host "End Update-Textbox [$(get-date)]"
Function Read-Textbox(){
write-host "`nBegin Read-Textbox [$(get-date)]"
$SyncHash.TXT_Output.Dispatcher.Invoke($Normal,[action]{$Global:Return = $SyncHash.TXT_Output.Text})
$Global:Return
remove-variable -Name Return -scope Global
write-host "End Read-Textbox [$(get-date)]"
#Give the form some time to load in the other runspace
$MaxWaitCycles = 5
while (($SyncHash.Form.IsInitialized -eq $Null)-and ($MaxWaitCycles -gt 0)){
Start-Sleep -Milliseconds 200
$MaxWaitCycles--
Update-ComboBox
Update-Textbox -Value $("Initial Load: $(get-date)")
Write-Host "Value Read From Textbox: $(Read-TextBox)"
Register-ObjectEvent -InputObject $SyncHash.CMB_Services -EventName SelectionChanged -SourceIdentifier "CMB_Services.SelectionChanged" -action {Update-Textbox -Value $("From Selection Changed Event: $(get-date)")}Thanks again for the responses. This may not be possible, but I thought I would throw it out there. I appreciate your help in looking into this.
To clarify the "Respond to control events in the main runspace"... I'm would like to have an event generated by a form object in the UI runspace (ex: combo box selectionchanged event) trigger a delegate within the main runspace and have that delegate in
the main runspace update the form in the UI runspace.
ex:
1.) User changes selection on combo box generating form event
2.) Event calls delegate (which I have gotten to work)
3.) Delegate does some basic processing (works)
4.) Delegate attempts to update form in UI runspace (hangs)
As to the delegates / which runspace they are running in. I see the $synchash variable if I run get-var within a delegate, but I do not see the $Form variable so I am assuming that they are in the main runspace. Do you agree with that assumption?
Maybe you are looking for
-
Embedded PDF - How to get hyperlinks to work?
Using APEX 4.1 - about to go to 4.2, Oracle 11g, IE9 I have PDFs stored in a table as a BLOB. I display them inline with the EMBED tag on a display item: RETURN '<object width="800" height="600" data="'||APEX_UTIL.GET_BLOB_FILE_SRC('P3_DIRECTIVE_PDF'
-
Very slow login windows 8.1
Hey people, i have a GT 72 QD 970m version. Recently I have been having an issue where changing between my integrated or dedicated graphics cards will make it wait a very long time (eg. 2 mins) before logging me into Windows (right after putting in m
-
How to remove PIE from Xperia C6902
How do I remove Position independent executables from Xperia z1 so that I can root? I have tried flashing it from Emma but Emma does not support C6902 Plz help
-
Multiple schemas assigned to a workspace
I'm trying to write an app that accesses other schemas besides the apex user I'm using. I can't figure out how to assign more than one schema to a workspace. All help is sincerely appreciated Rich
-
continuamente Currently each time I try to play Zynga page to arise adobe plugin crash. I uninstalled and reinstalled Adobe Flash and Macromedia products without success. Using Mozilla Firefox windows SP3 and ESR 10.0.4. That may be going before wor