Key in  HashSet

I want to insert my customized objects into HasSet but same time i want to ensure that it should not accept duplicate objects and also i want to insert the objects in sorted manner but the constraint here is i can o use only HashSet, so how i can do this.

Thanks for your valuable suggestion... i have tried following code but
its not preserving sorting..
class Car implements Comparable
private int x;
public int getX()
return x;
public int compareTo(Object o1)
System.out.println("conpare() called x="+x+"o1="+((Car)o1).getX());
if(x<((Car)o1).getX())
          return 1;
     else if(x>((Car)o1).getX())
          return -1;
     else return 0;
public Car(int x)
     this.x=x;
public boolean equals(Object o)
          System.out.println("equals Called");
          compareTo(o);
          if( ((Car)o).getX()==x )
               return true;
return false;
public int hashCode()
System.out.println("HashCode Called x="+x);
equals(this);
return x*2;
public String toString()
return String.valueOf(x);
public class HashTest2
public static void main(String[] argv)
Car c2= new Car(2);
Car c1 = new Car(1);
HashSet SET = new HashSet();
SET.add(new Car(3));
SET.add(c1);
SET.add(c2);
SET.add(new Car(3));
SET.add(new Car(13));
SET.add(new Car(10));
for(Object c: SET)
     System.out.println((Car)c);
}

Similar Messages

  • Shortcut key table

    I'm testing this table with key shortcuts:
    import java.util.HashSet;
    import java.util.Set;
    import javafx.application.Application;
    import javafx.beans.property.ReadOnlyObjectWrapper;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.TableView;
    import javafx.scene.control.cell.TextFieldTableCell;
    import javafx.scene.input.KeyCharacterCombination;
    import javafx.scene.input.KeyCode;
    import javafx.scene.input.KeyCombination;
    import javafx.scene.input.KeyEvent;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    public class test extends Application {
        public static void main(String[] args) {
            launch(test .class);
        @Override
        public void start(Stage stage) throws Exception {
            final ObservableList<KeyCharacterCombination> items = FXCollections.observableArrayList();
            for (int i = 0; i < 110; i++) {
                items.add(null);
            TableView<KeyCharacterCombination> table = new TableView<>(items);
            table.setEditable(true);
            final TableColumn<KeyCharacterCombination, KeyCharacterCombination> column = new TableColumn<>();
            column.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<KeyCharacterCombination, KeyCharacterCombination>, ObservableValue<KeyCharacterCombination>>() {
                @Override
                public ObservableValue<KeyCharacterCombination> call(TableColumn.CellDataFeatures<KeyCharacterCombination, KeyCharacterCombination> cellDataFeatures) {
                    return new ReadOnlyObjectWrapper<>(cellDataFeatures.getValue());
            column.setMinWidth(530);
            column.setCellFactory(new Callback<TableColumn<KeyCharacterCombination, KeyCharacterCombination>, TableCell<KeyCharacterCombination, KeyCharacterCombination>>() {
                @Override
                public TableCell<KeyCharacterCombination, KeyCharacterCombination> call(TableColumn<KeyCharacterCombination, KeyCharacterCombination> tableColumn) {
                    final TableCell<KeyCharacterCombination, KeyCharacterCombination> cell = new TextFieldTableCell<KeyCharacterCombination, KeyCharacterCombination>() {
                        @Override
                        public void updateItem(KeyCharacterCombination keyCharacterCombination, boolean b) {
                            super.updateItem(keyCharacterCombination, b);
                            if (this.getItem() == null || b) {
                                setText(null);
                            } else {
                                StringBuilder sb = new StringBuilder();
                                if (keyCharacterCombination.getControl() == KeyCombination.ModifierValue.DOWN) {
                                    sb.append("Ctrl + ");
                                if (keyCharacterCombination.getAlt() == KeyCombination.ModifierValue.DOWN) {
                                    sb.append("Alt + ");
                                if (keyCharacterCombination.getShift()== KeyCombination.ModifierValue.DOWN) {
                                    sb.append("Shift + ");
                                sb.append(keyCharacterCombination.getCharacter());
                                setText(sb.toString());
                    cell.setOnKeyPressed(new EventHandler<KeyEvent>() {
                        Set<KeyCombination.Modifier> keys = new HashSet<>();
                        @Override
                        public void handle(KeyEvent keyEvent) {
                            if (keyEvent.getCode() == KeyCode.CONTROL) {
                                keys.add(KeyCombination.CONTROL_DOWN);
                            } else if (keyEvent.getCode() == KeyCode.ALT) {
                                keys.add(KeyCombination.ALT_DOWN);
                            } else if (keyEvent.getCode() == KeyCode.SHIFT) {
                                keys.add(KeyCombination.SHIFT_DOWN);
                            } else if (keyEvent.getCode().isLetterKey()) {
                                items.set(cell.getIndex(), new KeyCharacterCombination(keyEvent.getCode().getName(),
                                        keys.toArray(new KeyCombination.Modifier[keys.size()])));
                                keys.clear();
                    return cell;
            table.getColumns().add(column);
            stage.setScene(new Scene(table));
            stage.show();
    There is problem which I cannot solve. For example I can set key combination Ctrl+'D' or Shift+Ctrl+Alt+'G' but I cannot use key combination like Ctrl + 'X' or Ctrl + 'Z'. Can you help to improve this code?

    Unfortunately, there are no shortcuts for this. Prior to the Oracle acquisition, Primavera had it as a goal for R7 to allow the operator to keep their hands on the keyboard most of the time, but this feature didn't make it into the final code. I feel your pain!

  • C++ API: is there a bug with Map::InvokeAll?

    Hello,
    I'm trying to use entry processors for doing like "put if absent", "delete where", ...
    I works fine except for the return values. Whatever I do, the map returned by InvokeAll is always empty!
    This a simple example:
    #include <coherence/net/cachefactory.hpp>
    #include <coherence/util/extractor/KeyExtractor.hpp>
    #include <coherence/util/filter/AlwaysFilter.hpp>
    #include <coherence/util/filter/LikeFilter.hpp>
    #include <coherence/util/filter/NotFilter.hpp>
    #include <coherence/util/filter/PresentFilter.hpp>
    #include <coherence/util/HashSet.hpp>
    #include <coherence/util/processor/ConditionalPutAll.hpp>
    #include <coherence/util/processor/ConditionalRemove.hpp>
    namespace ch = coherence::net;
    namespace cu = coherence::util;
    namespace cl = coherence::lang;
    namespace {
    void dumpMap(cu::Set::View vSetResult, const std::string &message)
    std::cerr<<message<<": ";
    for (cu::Iterator::Handle hIter = vSetResult->iterator(); hIter->hasNext(); )
    cu::Map::Entry::View vEntry = cl::cast<cu::Map::Entry::View>(hIter->next());
    cl::String::View key = cl::cast<cl::String::View>(vEntry->getKey());
    cl::String::View val = cl::cast<cl::String::View>(vEntry->getValue());
    std::cerr<<"("<<vEntry->getKey()<<","<<vEntry->getValue()<<"), ";
    std::cerr<<std::endl;
    void dumpCache(ch::NamedCache::Handle hCache, const std::string &message)
    dumpMap(hCache->entrySet(), message);
    void initCache(ch::NamedCache::Handle hCache)
    hCache->clear();
    hCache->put(cl::String::create("01"), cl::String::create("v:01"));
    hCache->put(cl::String::create("05"), cl::String::create("v:05"));
    hCache->put(cl::String::create("11"), cl::String::create("v:11"));
    hCache->put(cl::String::create("15"), cl::String::create("v:15"));
    hCache->put(cl::String::create("21"), cl::String::create("v:21"));
    hCache->put(cl::String::create("25"), cl::String::create("v:25"));
    void testInvokeAll()
    ch::NamedCache::Handle hCache(ch::CacheFactory::getCache("first_cache"));
    std::cerr<<"== init"<<std::endl;
    initCache(hCache);
    dumpCache(hCache, "init");
    std::cerr<<"== emulation putIfAbsent"<<std::endl;
    cu::Map::Handle entries = cu::HashMap::create();
    entries->put(cl::String::create("01"), cl::String::create("v:01MOD"));
    entries->put(cl::String::create("==="), cl::String::create("===MOD"));
    entries->put(cl::String::create("11"), cl::String::create("v:11MOD"));
    entries->put(cl::String::create("+++"), cl::String::create("+++MOD"));
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalPutAll::create(
    cu::filter::NotFilter::create(cu::filter::PresentFilter::getInstance()), entries);
    cu::Map::View res = hCache->invokeAll(cl::cast<cu::Collection::View>(entries->keySet()), processor);
    // BUG ? should return a result set of 4 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "putIfAbsent");
    std::cerr<<"== emulation delete where key in ('11', '===')"<<std::endl;
    cu::Set::Handle keys = cu::HashSet::create();
    keys->add(cl::String::View("11"));
    keys->add(cl::String::View("==="));
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalRemove::create(cu::filter::AlwaysFilter::getInstance(), true);
    cu::Map::View res = hCache->invokeAll(cl::cast<cu::Collection::View>(keys), processor);
    // BUG ? should return a result set of 2 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "delete where");
    std::cerr<<"== emulation delete where key like '2%'"<<std::endl;
    // should return entries as the corresponding flag is set to true
    cu::InvocableMap::EntryProcessor::Handle processor = cu::processor::ConditionalRemove::create(cu::filter::AlwaysFilter::getInstance(), true);
    cu::Filter::View f = cu::filter::LikeFilter::create(cu::extractor::KeyExtractor::create(), cl::String::create("2%"));
    cu::Map::View res = hCache->invokeAll(f, processor);
    // BUG ? should return a result set of 2 entries but returns an empty set
    std::cerr<<"res size "<<res->size()<<std::endl;
    dumpMap(res->entrySet(), "res");
    // The job has be done correctly
    dumpCache(hCache, "delete where2");
    int main(int argc, char** argv)
    try
    ch::CacheFactory::configure(ch::CacheFactory::loadXmlFile("client-cache-config.xml"));
    testInvokeAll();
    ch::CacheFactory::shutdown();
    catch(const cl::Exception::View &e)
    std::cerr<<"Ouch! "<<e<<std::endl;
    return 0;
    The output is:
    == init
    init: (11,v:11), (01,v:01), (25,v:25), (05,v:05), (21,v:21), (15,v:15),
    == emulation putIfAbsent
    res size 0
    res:
    putIfAbsent: (===,===MOD), (11,v:11), (01,v:01), (25,v:25), (+++,+++MOD), (05,v:05), (21,v:21), (15,v:15),
    == emulation delete where key in ('11', '===')
    res size 0
    res:
    delete where: (01,v:01), (25,v:25), (+++,+++MOD), (05,v:05), (21,v:21), (15,v:15),
    == emulation delete where key like '2%'
    res size 0
    res:
    delete where2: (01,v:01), (+++,+++MOD), (05,v:05), (15,v:15), The cache is modified as expected but the maps returned by invokeAll are always empty!
    Is it a bug? Do I understand the documentation incorrectly? Do I use the API incorrectly?

    Yes, I've noticed the difference between ConditionalPut and ConditionalPutAll. Ther constructor are:
    * Construct a ConditionalPut that updates an entry with a new value
    * if and only if the filter applied to the entry evaluates to true.
    * This processor optionally returns the current value as a result of
    * the invocation if it has not been updated (the filter evaluated to
    * false).
    * @param vFilter the filter to evaluate an entry
    * @param ohValue a value to update an entry with
    * @param fReturn specifies whether or not the processor should
    * return the current value in case it has not been
    * updated
    ConditionalPut(Filter::View vFilter, Object::Holder ohValue,
              bool fReturn = false);and
    * Construct a ConditionalPutAll processor that updates an entry with
    * a new value if and only if the filter applied to the entry
    * evaluates to true. The new value is extracted from the specified
    * map based on the entry's key.
    * @param vFilter the filter to evaluate all supplied entries
    * @param vMap a map of values to update entries with
    ConditionalPutAll(Filter::View vFilter, Map::View vMap);
    ConditionalPut has an extra flag for returning the new value. It does work with a call to invoke, I've tested it. Why can't we do the same with ConditionalPutAll? Do I have to N ConditionalPut instead of 1 ConditionalPutAll in order to know if my values have been updated?
    ConditionalRemove has the same flag than ConditionalPut:
    * Construct a ConditionalRemove processor that removes an
    * InvocableMap entry if and only if the filter applied to the entry
    * evaluates to true.
    * This processor may optionally return the current value as a result
    * of the invocation if it has not been removed (the filter evaluated
    * to false).
    * @param vFilter the filter to evaluate an entry
    * @param fReturn specifies whether or not the processor should
    * return the current value if it has not been removed
    ConditionalRemove(Filter::View vFilter, bool fReturn = false);But when used with invokeAll, it doesn't return any value as shown in the example I've sent. Is it a bug or a designed feature?

  • HashCode

    Hi all,
    I studied some docs reagarding hashCode() and have some questions.
    From: java.lang.Object: hashCode():
    1) "Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application." Why?
    2) From: Java Glossory: http://www.mindprod.com/jgloss/hashcode.html
    Object.hashCode Implementation: The default hashCode() method uses the 32-bit internal JVM address of the Object as its hashCode. However, if the Object is moved in memory during garbage collection, the hashCode stays constant. This default hashCode is not very useful, since to look up an Object in a HashMap, you need the exact same key Object by which the key/value pair was originally filed. Normally, when you go to look up, you don't have the original key Object itself (Why?)
    just some data for a key. So, unless your key is a String, nearly always you will need to implement a hashCode and equals method on your key class.
    3) From the same text:
    "As a rule of thumb, any time you use an Object as a key in a Map or Set (e.g. Hashtable, HashMap, HashSet, TreeMap etc.) you must redefine both equals and hashCode in such a way both incorporate all the fields of the logical key. Fields in the key Object irrelevant to lookup should not be included in either method."
    Why do I need to implement the hashCode() method anyway? Why the 32-bit internal JVM address of the Object which is returned from hashCode() method wouldn't be enough to give me the key I need?
    4) From Java theory and practice: Hashing it out: http://www-128.ibm.com/developerworks/java/library/j-jtp05273.html
    "Why override equals() and hashCode()?
    What would happen if Integer did not override equals() and hashCode()? Nothing, if we never used an Integer as a key in a HashMap or other hash-based collection. However, if we were to use such an Integer object for a key in a HashMap, we would not be able to reliably retrieve the associated value, unless we used the exact same Integer instance in the get() call as we did in the put() call. This would require ensuring that we only use a single instance of the Integer object corresponding to a particular integer value throughout our program. Needless to say, this approach would be inconvenient and error prone."
    Why its error prone? Why can't we say that we are using the same instance of the Integer object?
    5) Why do I need to override hashCode() for HashSet? We don't have the concept of key in HashSet?
    6) Its also said that no matter what algorithm is used for calculating hashCode, its possible that two non-equal objects have the same hashCode, so if we are using those objects as keys in HashTable, how can we avoid having the same hashCode or the same key for two different values? On the other word, how can we avoid collisions, (if there is anyway) ?
    I stopped going through more documents at this point, since it seems more questions will arise! If I know the answer to the above questions it will help to understand the rest of document. Any help is greatly appreciated.

    comparisons on the object is modified. This
    integer need not remain consistent from one execution
    of an application to another execution of the same
    application." Why? Because there's no reason to do so. HashCode isn't intended as a persistent identifier for an object. It's simply intended as a fingerprint of the object's current state.
    key/value pair was originally filed. Normally,
    when you go to look up, you don't have the original
    key Object itself (Why?) I do map.put(joe.name, joe) later, when somebody asks for the object named "joe"--using the String "joe"--I use that to do person = map.get(requestedName); . When the string "joe" comes in, that lookup is how I find the associated object.
    hy do I need to implement the hashCode() method
    anyway? Why the 32-bit internal JVM address of the
    Object which is returned from hashCode() method
    wouldn't be enough to give me the key I need? Hashcode cannot use any data that equals does not use. The default hashCode uses (in general, and roughly) the object's address.
    The way a hashMap works is you use the object's hashCode to get to the right bucket--the small subset of all the entries that might potentially match--and then do a linear search on the bucket using equals.
    If I say map.get("joe"), the get method first computes the hashCode of the "joe" String object. Every time I provide "joe", I have to get the same hashCode, in order to get the right bucket--the right subset--to search. If String didn't override hashCode, then two different "joe"String objects would have two different hashCodes, and I'd never be able to zoom in on the bucket containing the "joe" entry.
    Likewise, any object that you want to use as a key in a HashMap, or store in a HashSet, must override hashCode so that the hashCode can be used to find the correct subset that might contain an entry for which equals() is true.
    http://en.wikipedia.org/wiki/Hashing
    Why its error prone? Why can't we say that we are
    using the same instance of the Integer object? I don't have the time to explain this any more. Read the wiki link above, or an introductory text on data structures.

  • Can you create an index on a Map?

    I have a few questions that I can't seem to figure out nor find a viable example for. Can you create an index for a Map contained within a nested object, and if so, how would you do this? I currently have a Filter the inspects this criteria in the cache but am unable to figure out to create a usabe index for the custom filter. I'm using Coherence 3.5.2 - any help would be most appreciated. I'm not sure if/what I need to do with the SimpleMapIndex....
    Here's the basic object map below. My filter is retrieving all of the CustomerGroup objects that have a Customer in it's collection that contains the passed in Integer value in the Customer's Map. So can you create an Index on a Map (and a nested one at that) and how do you that? The index would need to be on the nested customerValues hashmap.
    class CustomerGroup
        Set<Customer> customers ;
    class Customer
        Map<Integer, CustumerValue> customerValues;
    }

    If you write a custom ValueExtractor, which you need to create an index, then you will not need a custom Filter.
    Depending on how efficient you need to be you custom extractor can use POF and not have to deserialize the entries to create the index, or it can deserialize the class, which will make the code more straight forward.
    For example, without using POF
    public class MapKeyExtractor extends EntryExtractor implements PortableObject {
        public MapKeyExtractor() {
        @Override
        public Object extractFromEntry(Map.Entry entry) {
            Set<Integer> keys = new HashSet<Integer>();
            CustomerGroup group = (CustomerGroup) entry.getValue();
            Set<Customer> customers = group.getCustomers();
            for (Customer customer : customers) {
                keys.addAll(customer.getCustomerValues().keySet());
            return keys;
        @Override
        public boolean equals(Object obj) {
            return (obj instanceof MapKeyExtractor);
        @Override
        public int hashCode() {
            return MapKeyExtractor.class.hashCode();
        @Override
        public void readExternal(PofReader in) throws IOException {
            super.readExternal(in);
        @Override
        public void writeExternal(PofWriter out) throws IOException {
            super.writeExternal(out);
    }The extractor above will return a collection of all of the Integer values in the keys of all the customerValues of all the customers in a CustomerGroup (I have guessed you might have accessor methods on the classes you posted).
    You can then use a ContainsFilter for your query. For example to get all the values from the cache where the customerValues map contains a 19 in the key...
    Set results = cache.entrySet(new ContainsFilter(new MapKeyExtractor(), 19));You could write a version of the MapKeyExtractor that uses POF and would not deserialize the values but this would be more complicated code as it would need to extract the Map from the POF stream of the value and walk down the keys and values extracting the keys. It is doable but not worth it unless you are really worried about performance of index updates.
    Discalimer I have written the code above from the top of my head so have not compiled it or tested it but it should be OK.
    JK

  • About  FocusTraversal  in JList

    Hi all , I'm building up a mini dictionary ,I 've done the rest of my program and this is just an extra , when the user input the
    character "L" into the textfield then the List of word will point to the first word of
    all the words that consist "L" , so on.......as the figure in the below link :
    http://i196.photobucket.com/albums/aa69/emperor1412/Question.jpgI have find out that swing has some methods about " FocusTraversal " to support JList , I've try to connect the " FocusTraversal " of my List to the " Textfield " so that the " Textfield " can control it but unsuccessfull, can anyone spend a moment to solve this problem by using anything about " FocusTraversal " , I can solve this problem by another way but I want to know how this problem can be solve by using " FocusTraversal " .
    Here is the link of database for dictionary ( this file is *{color:#ff0000}compulsory{color}* to run this program):
    http://6636676817799962274-a-greenmekong-com-s-sites.googlegroups.com/a/greenmekong.com/nguyenhailong/teaching/dicData.rar?attredirects=0 *( no virus )*
    or
    http://nguyenhailong.greenmekong.com/teaching ( file DicData.rar )
    These are 5 classes of my program , just copy and buit it , it already worked :
    1.Class Data
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.Vector;
    public class Data implements Serializable{
        private List<String> Data;
        public Data()
            Data = new Vector<String>(104966);
        public void add(String data)
            Data.add(data);
        public String get(int index)
            String entireSentence="";
            String data = Data.get(index);
            StringTokenizer seperatedWord = new StringTokenizer(data);
            List<String> temp = new ArrayList<String>();
            while(seperatedWord.hasMoreElements())
                temp.add((String)seperatedWord.nextElement());
            Iterator iterator = temp.iterator();
            while(iterator.hasNext())
                boolean flag = false;
                String word = (String)iterator.next();
                for(int k = 0 ; k < word.length(); k++ )
                    if(word.charAt(k)=='\\' && word.charAt(k+1)=='n')
                        entireSentence = entireSentence +"  "+ word.substring(0, k)
                                + "\n" +"  "+ word.substring(k+2,word.length()) ;
                        flag = true;
                        break;
                if(!flag)   entireSentence += (word+"  ");
            return entireSentence;
        public List<String> getData() {
            return Data;
        public void setData(List<String> Data) {
            this.Data = Data;
    2.Class DicData
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.Serializable;
    import java.util.List;
    import java.util.Scanner;
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.util.Vector;
    import javax.swing.JOptionPane;
    * @author kaka
    public class DicData implements Serializable{
        static ObjectOutputStream output;
        static ObjectInputStream input;
        private List<WordIndex> wordindex;
        private Data data;
        private int numofword=0;
        public DicData(String path) throws Exception
            boolean flag = false;
            wordindex = new Vector<WordIndex>(104966);
            data = new Data();
            try{
                Scanner in = new Scanner(new FileInputStream(path),"UTF-8");
                while(in.hasNext()) {                       
                    String Line = in.nextLine();
                    String Word ="";
                    for(int i = 0 ;i < Line.length() ; i++ ) {
                        if(Line.charAt(i)=='[' )
                            Word = Line.substring(0, i-1);
                            Word = Word.trim();
                            Word = Word.toLowerCase();
                            break;
                        if(Line.charAt(i)==' ' && Line.charAt(i-1)=='-') {
                            if(Line.charAt(i-2) == '\t') {
                                Word = Line.substring(0, i-1);
                                Word = Word.trim();
                                Word = Word.toLowerCase();
                                break;
                            if(Line.charAt(i-2) != '\t' ) {
                                Word = Line.substring(0, i);
                                Word = Word.trim();
                                Word = Word.toLowerCase();
                                break;
                wordindex.add(new WordIndex(Word,numofword));           
                data.add(Line);
                ++numofword;
            catch(Exception exception){
                JOptionPane.showMessageDialog(null, "Invalid path");
                System.exit(1);
        public static void saveRecord(DicData dicdata) throws Exception
             try {
                output = new ObjectOutputStream(new FileOutputStream(new File("DictionaryData.ser")));
             catch ( Exception exception ){
                System.err.println( "Error opening file." );
             try{
                output.writeObject(dicdata);
                JOptionPane.showMessageDialog(null,"Database saved successfully");
             catch ( Exception exception ){
                   System.err.println( "Error writing to file." );
        public static DicData loadRecord() throws Exception {
            input = new ObjectInputStream(new FileInputStream("DictionaryData.ser"));
            return (DicData) input.readObject();
        public static void closeFileoutput()
            try {
            if(output!=null)
                output.close();
            catch(Exception exception) {
                System.err.println("Error closing file");
                System.exit(1);
        public static void closeFileinput()
            try {
            if(input!=null)
                input.close();
            catch(Exception exception) {
                System.err.println("Error closing file");
                System.exit(1);
        public Data getData() {
            return data;
        public void setData(Data data) {
            this.data = data;
        public int getNumofword() {
            return numofword;
        public void setNumofword(int numofword) {
            this.numofword = numofword;
        public List<WordIndex> getWordindex() {
            return wordindex;
        public void setWordindex(List<WordIndex> wordindex) {
            this.wordindex = wordindex;
    3.Class HashingDic
    import java.io.Serializable;
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.util.Hashtable;
    import java.util.List;
    import java.util.Iterator;
    import javax.swing.JOptionPane;
    * @author kaka
    public class HashingDic implements Serializable{
        protected Hashtable table;
        public HashingDic(DicData data)
            table = new Hashtable();
            List<WordIndex> wordindex = data.getWordindex();
            Iterator it = wordindex.iterator();
            while(it.hasNext())
                WordIndex temp = (WordIndex)it.next();
                table.put( temp.getKey(),temp.getIndex() );
        public int Search(String keyword)
            try{
            return (Integer) table.get(keyword);  
            catch(NullPointerException nullPointerException)
                JOptionPane.showMessageDialog(null,"Word not found");
                return -1;
    4.Class WordIndex
    import java.io.Serializable;
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    * @author kaka
    public class WordIndex implements Serializable {
        private String Key;
        private Integer Index;
        public WordIndex(){}
        public WordIndex(String word,int index)
            Key = word;
            Index = index;
        public Integer getIndex() {
            return Index;
        public void setIndex(Integer Index) {
            this.Index = Index;
        public String getKey() {
            return Key;
        public void setKey(String Key) {
            this.Key = Key;
    5.Class Main
    *import java.awt.BorderLayout;*
    *import java.awt.Color;*
    *import java.awt.Container;*
    *import java.awt.Panel;*
    *import java.awt.event.ActionEvent;*
    *import java.awt.event.ActionListener;*
    *import java.util.HashSet;*
    *import java.util.Iterator;*
    *import java.util.List;*
    *import java.util.Set;*
    *import java.util.Vector;*
    *import javax.swing.JButton;*
    *import javax.swing.JFileChooser;*
    *import javax.swing.JFrame;*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.KeyStroke;
    import javax.swing.ListSelectionModel;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    * @author kaka
    public class Main extends JFrame implements ActionListener {
        private JButton Search;
        private JTextField TextField;
        private JList List;
        private JTextArea TextArea;
        private Container container;
        private JLabel Label;
        private JScrollPane Scroll;
        private JScrollPane ScrollPane;
        private DicData data ;
        private HashingDic hashData ;
        private Vector<String> keywords;
        Set<KeyStroke> key = new HashSet<KeyStroke>();
        //private KeyStroke keystroke;
        public Main(){
        super("Dictionary - Author : &#272;uc-Ho&agrave;ng-Giang-Group ");
        super.setResizable(false);
        public void runGraphic()
            container = this.getContentPane();
            BorderLayout layout = new BorderLayout();
            container.setLayout(layout);
            Label = new JLabel("Input word here ");
            TextField = new JTextField(20);
            TextField.addActionListener(this);
            Search = new JButton("Search");
            Search.addActionListener(this);
            Panel panel1 = new Panel();
                panel1.add(Label);
                panel1.add(TextField);
                panel1.add(Search);
            TextArea = new JTextArea( 26, 40);
            TextArea.setBackground(Color.WHITE);
            TextArea.setEditable(false); // the information about the meaning of word can not be edit
            Panel panel2 = new Panel();
            Scroll = new JScrollPane(TextArea);
                panel2.add(Scroll);
            List = new JList(keywords);
            List.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            List.setFixedCellWidth(180);
            List.addListSelectionListener(new ListSelectionListener()
                public void valueChanged(ListSelectionEvent e) {
                    int index = List.getSelectedIndex();               
                    TextArea.setText(data.getData().get(index));
                    TextArea.setCaretPosition(0);
            ScrollPane = new JScrollPane(List);
                    container.add(panel1,BorderLayout.NORTH);
                    container.add(panel2,BorderLayout.EAST);
                    container.add(ScrollPane,BorderLayout.WEST);
            this.setSize(700, 500);
            this.setVisible(true);
        public static void main(String args[]) throws Exception
            Main test = new Main();
            test.runSource();
            test.runGraphic();
            test.setDefaultCloseOperation(EXIT_ON_CLOSE);
        public void runSource() throws Exception
            try{
                //long start = System.currentTimeMillis();
                data = DicData.loadRecord();
                hashData = new HashingDic(data);
                keywords = new Vector<String>(104966);
                List<WordIndex> words = data.getWordindex();
                Iterator it = words.iterator();
                while(it.hasNext())
                    WordIndex temp = (WordIndex) it.next();
                    keywords.add(temp.getKey());
                JOptionPane.showMessageDialog(null,"Database loaded successfully ");
                DicData.closeFileoutput();
                /*long end = System.currentTimeMillis();
                JOptionPane.showMessageDialog(null,"Duration : " + (end - start)
                        + "\n Num of words : " + data.getNumofword());*/
            catch(Exception exception)
                JOptionPane.showMessageDialog(null,"Database loaded failed ");
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
                int result = chooser.showOpenDialog(this);
                if(result == JFileChooser.CANCEL_OPTION)   System.exit(1);
                String path = chooser.getSelectedFile().getAbsolutePath();
                //String path = JOptionPane.showInputDialog("Input path of database : ");
                //long start = System.currentTimeMillis();
                data = new DicData(path);
                hashData = new HashingDic(data);
                JOptionPane.showMessageDialog(null,"Database created successfully ");
                DicData.closeFileinput();
                DicData.saveRecord(data);
                List<WordIndex> words = data.getWordindex();
                Iterator it = words.iterator();
                keywords = new Vector<String>(104966);
                while(it.hasNext())
                    WordIndex temp = (WordIndex) it.next();
                    keywords.add(temp.getKey());
                /*long end = System.currentTimeMillis();
                JOptionPane.showMessageDialog(null,"Duration : " + (end - start)
                        + "\n Num of words : " + data.getNumofword());*/
        public void actionPerformed(ActionEvent e) {
            if( e.getSource() == TextField || e.getSource() == Search )
                String a = TextField.getText();
                a = a.toLowerCase();
                a = a.trim();
                int returnValue = hashData.Search(a);
                if(returnValue!=-1)
                TextArea.setText(data.getData().get(returnValue));
                TextArea.setCaretPosition(0);  //put the prompt at the begining of the text
    }Edited by: keomanla on Sep 5, 2008 11:17 PM
    Edited by: keomanla on Sep 5, 2008 11:17 PM
    Edited by: keomanla on Sep 5, 2008 11:18 PM
    Edited by: keomanla on Sep 5, 2008 11:19 PM
    Edited by: keomanla on Sep 5, 2008 11:19 PM
    Edited by: keomanla on Sep 5, 2008 11:22 PM
    Edited by: keomanla on Sep 5, 2008 11:24 PM
    Edited by: keomanla on Sep 5, 2008 11:42 PM
    Edited by: keomanla on Sep 5, 2008 11:43 PM
    Edited by: keomanla on Sep 6, 2008 12:43 AM

    You could still use HTML, but I guess then the problem would be the image on the button.
    Alternatively, you could subclass JToolTip, create the ui you want, and install it on the JList by overriding the necessary tooltip methods in JList (I think getToolTip). Search the forums (serach field on the left) for more on this approach.
    A third approach would be to re-invent the wheel using JWindow and a Timer to achieve the appearance and effect you want.
    ICE

  • Please Help::How to display a Map with LIsts as Keys and Values using JSTL

    Hi,
    I need some assistance on how to display a Map in JSP using struts or core JSTL. I have a HashMap which has a List of keys and each key maps to a value of an ArrayList.i.e I have an ArrayList of taxCodes and each taxCode maps to a value of taxDetails which is an ArrayList of details for for that particular taxCode. I have some trouble to display each taxCode then display taxDetails for each taxCode. Here is my code below:
    OrderDetails.java
    package orderitems;
    import java.sql.*;
    import java.util.*;
    public class OrderDetails {
        private LineOder lineOrder;
        private Map lineItems;
        //returns an item number, key_item, from its unique keys
        public int getItemNumber(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            int itmNum = 0;
             * key_item a unique number for an item.
             * key_year,key_office,key_client,key_company unique keys
             * for each order where this key_item is taken
             * from.
            String select = "SELECT key_item FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + key_item +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                if(rst.next()){
                    itmNum = Integer.parseInt(rst.getString("key_item"));
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itmNum;
        //get a list of item number(item codes)
        public List getAllItemNumbers(String key_year,
                String key_office,String key_client,String key_company){
            List itemNumbers = new ArrayList();
            LineItem itemNumber = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            String select = "SELECT key_item FROM "+ Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    itemNumber = new LineItem();
                    itemNumber.setKey_item(Integer.parseInt(rst.getString("key_item")));
                    itemNumbers.add(itemNumber);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemNumbers;
        //get a list of tax codes
        public List getAllTaxCodes(int key_item, String key_year,
                String key_office,String key_client,String key_company){
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            ItemTax taxCode;
            List taxCodes = new ArrayList();
            int itemNum = getItemNumber(key_item, key_year,
                    key_office,key_client,key_company);
            String select = "SELECT key_tax_code FROM "+
                    Constants.WEB_TABLE +" WHERE key_item = " + itemNum +
                    " AND key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company +"'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    taxCode = new ItemTax();
                    taxCode.setKey_tax_code(rst.getString("key_tax_code"));
                    taxCodes.add(taxCode);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return taxCodes;
        /////This methode returns a Map which am trying to display in JSP
        //use tax code to get tax details
        public Map getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
                System.out.println();
                System.out.println("*********CONSOLE OUTPUT*************");//display on console
                Set set = itemTaxDetails.keySet();
                Iterator iter = set.iterator();
                System.out.println("Key\t\tValue\r\n");
                while (iter.hasNext()) {
                    Object taxCode=iter.next();
                    Object details=itemTaxDetails.get(taxCode);
                    System.out.println(taxCode +"\t" + details);
                System.out.println("************************************");
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return itemTaxDetails;
        //details of an item with all its taxes
        public List getAllItemDetails(String key_year,
                String key_office,String key_client,String key_company){
            List lineItems = new ArrayList();
            List itemNumbers = new ArrayList();
            Map taxDetails = new HashMap();
            LineItem item = null;
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //A list of all item numbers in the declaration
            itemNumbers = getAllItemNumbers(key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator itemIter= itemNumbers.iterator(); itemIter.hasNext();){
                    LineItem itemNum = (LineItem)itemIter.next();
                    int itemNumber = itemNum.getKey_item();
                    String select = "SELECT item_description,item_mass," +
                            "item_cost" +
                            " FROM " + Constants.WEB_TABLE +
                            " WHERE key_year = '"+key_year+"'" +
                            " AND key_office = '"+key_office+ "'"+
                            " AND key_client = '"+key_client+ "'"+
                            " AND key_company = '"+key_company+ "'"+
                            " AND key_item = " + itemNumber;
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        item = new LineItem();
                        item.setItem_description(rst.getString("item_description"));
                        item.setItem_mass(Float.parseFloat(rst.getString("item_mass")));
                        item.setKey_item(Integer.parseInt(rst.getString("item_cost")));
                        //////other details records ommited//////////////////////////
                        /* A HashMap of all itemTaxeCodes as its keys and an
                         * ArrayList of itemTaxedetails as its values
                        taxDetails = getItemTaxDetails(item.getKey_year(),item.getKey_office(),
                                item.getKey_client(),item.getKey_company(),item.getKey_item());
                        //item tax details
                        item.setItmTaxes(taxDetails);
                        //list of items with tax details
                        lineItems.add(item);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineItems;
        public Set getOrders(String key_year,String key_office,
                String key_client,String key_company){
            List lineItems = new ArrayList();
            Set lineOrders = new HashSet();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            LineOder lineOrder = null;
            String select = "SELECT * FROM " + Constants.WEB_TABLE +
                    " WHERE key_year = '" + key_year + "'" +
                    " AND key_office = '" + key_office + "'" +
                    " AND key_client = '" + key_client + "'" +
                    " AND key_company = '" + key_company + "'";
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                rst = stat.executeQuery(select);
                while(rst.next()){
                    lineOrder = new LineOder();
                    lineOrder.setKey_year(rst.getString("key_year"));
                    lineOrder.setKey_office(rst.getString("key_office"));
                    lineOrder.setKey_client(rst.getString("key_client"));
                    lineOrder.setKey_company(rst.getString("key_company"));
                    ////list of items with all their details
                    lineItems = getAllItemDetails(lineOrder.getKey_year(),lineOrder.getKey_office(),
                            lineOrder.getKey_client(),lineOrder.getKey_company());
                    //setting item details
                    lineOrder.setItems(lineItems);
                    //a list of order with all details
                    lineOrders.add(lineOrder);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            return lineOrders;
    Controller.java
    package orderitems;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Controller extends HttpServlet {
        private Map taxDetails = new HashMap();
        private OrderDetails orderDetails = null;
        protected void processRequest(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            String key_year = "2007";
            String key_office = "VZX00";
            String key_company = "DG20";
            String key_client =  "ZI001";
            int key_item = 1;
            String nextView = "/taxdetails_list.jsp";
            orderDetails = new OrderDetails();
            taxDetails = orderDetails.getItemTaxDetails(key_year,key_office,
                    key_company,key_client,key_item);
            //Store the collection objects into HTTP Request
            request.setAttribute("taxDetails", taxDetails);
            RequestDispatcher reqstDisp =
                    getServletContext().getRequestDispatcher(nextView);
            reqstDisp.forward(request,response);
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request,
                HttpServletResponse response)throws
                ServletException, IOException {
            processRequest(request, response);
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <title>Simple Tax Detail Diaplay ::</title>
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <jsp:useBean id="taxDetails" class="java.util.HashMap" scope="request"/>
            <table>
                <c:forEach items="${taxDetails}" var="hMap">
                    <tr>
                        <td><c:out value="${hMap.key}" /></td>
                        <!--td><%--c:out value="${hMap.value}" /--%></td-->
                    </tr>
                </c:forEach>
            </table>
        </body>
    </html>am displaying taxCodes(in this case i have VAT and ICD) fine but cant figure out how to display a list of value for each taxCode.Here is the output am getting
    both in my JSP and on the console:
    *******************************CONSOLE OUTPUT****************************
    Key          Value
    ICD     [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    VAT [orderItems.ItemTax@13e6226, orderItems.ItemTax@9dca26]
    Edited by: aiEx on Oct 8, 2007 6:54 AM

    hi evnafets,
    yes i need a nested for loop.I have tried your advice but my bean properties are not found.Am getting this error:
    javax.servlet.ServletException: Unable to find a value for "key_item" in object of class "java.lang.String" using operator "."
    I have tried this as stated earlier in the post:I have tried to make the method getItemTaxDetails return a List and get the returned list value as taxDetails. I then tested to display this list on JSP and its displaying fine.
    public List getItemTaxDetails(String key_year,String key_office,
                String key_client,String key_company,int key_item){
            ItemTax taxDetail = null;
            List taxDetails = new ArrayList();
            List itemTaxCodes = new ArrayList();
            Map itemTaxDetails = new HashMap();
            Connection conn = null;
            Statement stat = null;
            ResultSet rst = null;
            //get a list of all tax codes of an item with a
            //given item number
            itemTaxCodes = getAllTaxCodes(key_item,key_year,
                    key_office,key_client,key_company);
            DbConnection dbConn = new DbConnection();
            try {
                conn = dbConn.getDbConnection(Constants.WEB_JNDI);
                stat = conn.createStatement();
                for(Iterator taxCodeIter= itemTaxCodes.iterator(); taxCodeIter.hasNext();){
                    ItemTax itemTaxCode = (ItemTax)taxCodeIter.next();
                    String taxCode = itemTaxCode.getKey_tax_code();
                    String select = "SELECT tax_type,tax_value," +
                            "tax_limit_val FROM "+ Constants.WEB_TABLE +
                            " WHERE key_item = "+ key_item +
                            " AND key_year = '" + key_year + "'" +
                            " AND key_office = '" + key_office + "'" +
                            " AND key_client = '" + key_client + "'" +
                            " AND key_company = '" + key_company +"'" +
                            " AND key_tax_code = '" + taxCode + "'";
                    rst = stat.executeQuery(select);
                    while(rst.next()){
                        taxDetail = new ItemTax();
                        //records to be displayed only
                        taxDetail.setKey_item(Integer.parseInt(rst.getString("key_item")));
                        taxDetail.setTax_value(rst.getString("tax_value"));
                        taxDetail.setTax_limit_val(Float.parseFloat(rst.getString("tax_limit_val")));
                        //////other details records ommited//////////////////////////
                        taxDetails.add(taxDetail);////An ArrayList of taxDetails for each taxCode
                     * A HashMap which has all taxCodes of an item as its keys
                     * and an ArrayList of taxdetails as its values.
                     * I return this for display in a JSP.
                    itemTaxDetails.put(taxCode,taxDetails);
            } catch (SQLException ex) {
                ex.printStackTrace();
            } finally{
                SQLHelper.cleanUp(rst, stat, conn);
            //return itemTaxDetails;
            return taxDetails;
        }And my JSP
    taxdetails_list.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <link rel="stylesheet" type="text/css" href="imgs/orders.css"/>
        </head>
        <body>
            <table>
                <c:forEach var="curRecord" items="${taxDetails}" varStatus="rowCounter">
                        <c:choose>
                            <c:when test="${rowCounter.count % 2 == 0}">
                                <c:set var="rowStyle" scope="page" value="odd" />
                            </c:when>
                            <c:otherwise>
                                <c:set var="rowStyle" scope="page" value="even" />
                            </c:otherwise>
                        </c:choose>
                        <tr class="${rowStyle}">
                            <td>${curRecord.key_item}</td>
                            <td>${curRecord.tax_value}</td>
                            <td>${curRecord.tax_limit_val}</td>
                        </tr>
                    </c:forEach>
            </table>
        </body>
    </html>I can't see where am going wrong even with your advice.Please help.
    Thnx.

  • Hacking application id equals() to allow more than one row per "primary key"

    I have a read only entity whose primary key is not the real primary key
    on the underlying table. The result is that I get more than one row per
    "primary key". This is what I want. However KODO will not allow me do
    it, because I am storing the collection in a HashSet() and the equals()
    method on the application id object ensures that this set contains no
    duplicates (as defined by the application id). At least thats how it
    seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

    The "primary key" I am using it already a compound key of two columns.
    The real key on the underlying table is a three column key. But the
    problem is that the table represents two different application level
    entities. I could deal with it when I was hand-writing SQL (I could do
    a distinct for example) but now I am relying on foreign key
    relationships since I moved to JDO. Not sure what to do. Best solution
    is to rework the table, but there is a lot of legacy code (that other
    teams use and maintain) relying on this table. I guess I'll use the
    weekend for inspiration ;-)
    Steve Kim wrote:
    This sounds like a dangerous operation. Even if this works now, I
    cannot promise future compatibility... and in fact may result in bad
    data (for example in caching both at the PM and PMF level) Is there no
    other field that you can reference as part of the primary key? Primary
    Keys can be multi columned (e.g. last_name, soc_sec_number)
    Mike Hogan wrote:
    I have a read only entity whose primary key is not the real primary
    key on the underlying table. The result is that I get more than one
    row per "primary key". This is what I want. However KODO will not
    allow me do it, because I am storing the collection in a HashSet() and
    the equals() method on the application id object ensures that this set
    contains no duplicates (as defined by the application id). At least
    thats how it seems to behave.
    So, I have hacked the equals() method to do this:
    public boolean equals (Object ob)
    if (this == ob)
    return true;
    // Doing this because we expect more than one row from
    // REF_CODES for the same domain/shortCode combination.
    // This is ok to do (I guess?) as long as we are only
    // doing selects using this class.
    return false;
    Will this hack have any side effects? Is there another option? Like
    using a list collection? Is so, which collections are supported?
    Thanks,
    Mike.

  • Primary key based on multiple fields which are of a custom class type

    Hello!
    I have the following two classes.
    public class Application
    protected String appName;
    protected Set moduleOptions = new HashSet(); //Set<ModuleOption>
    public class Option
    protected String name;
    protected Application application;
    Now, I need for Option to have a composite primary key based on both its
    fields. How do I do this?
    For starters, I just need a few hints on how this should be done in Kodo
    because I already have this thing working in JPOX and that solution does
    not map directly to Kodo. JPOX defines the OptionPK (primary key class)
    to contain field ApplicationPK, and not Application. But Kodo does not
    accept this because of a mismatch between fields in class and its primary
    key class. (Not implying that Kodo should accept the same kind of
    solution.)
    Btw, I'm evaluating version 3.2.3.
    Thanks in advance!

    Viktor,
    The typical Kodo pattern for doing this is to create a private field in
    Option for each primary key in Application, map those fields as
    primary-key (but not the field of type Application), and therefore put
    those fields in the OptionPK. These fields should then be mapped to the
    same columns as the Application reference. Then, set the primary key
    fields to the same value as they are in the related object.
    Kodo allows multiple fields to be mapped to the same column in the
    database, and throws an exception if your actions would set the column
    to different values. So, typically, this might look like:
    public class Application
    protected String appName; // I'm assuming that this is the PK
    protected Set moduleOptions = new HashSet ();
    public class Option
    protected String name; // pk
    protected Application application; // not pk
    private String applicationAppName; // pk
    public Option (String n, Application a)
    name = n;
    application = a;
    applicationAppName = a.appName;
    -Patrick
    Viktor Matic wrote:
    Hello!
    I have the following two classes.
    public class Application
    protected String appName;
    protected Set moduleOptions = new HashSet(); //Set<ModuleOption>
    public class Option
    protected String name;
    protected Application application;
    Now, I need for Option to have a composite primary key based on both its
    fields. How do I do this?
    For starters, I just need a few hints on how this should be done in Kodo
    because I already have this thing working in JPOX and that solution does
    not map directly to Kodo. JPOX defines the OptionPK (primary key class)
    to contain field ApplicationPK, and not Application. But Kodo does not
    accept this because of a mismatch between fields in class and its primary
    key class. (Not implying that Kodo should accept the same kind of
    solution.)
    Btw, I'm evaluating version 3.2.3.
    Thanks in advance!

  • Key Handler

    //My source code:
    package keyhandler;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.Collections;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import javax.swing.JFrame;
    public class Handler implements KeyListener {
    private boolean FINISH = true;
    private Set<Integer> set;
    *@param args*
    public Handler() {
    set = Collections.synchronizedSet(new HashSet<Integer>());
    public void handle() {
    while (FINISH) {
    synchronized (set) {
    Iterator<Integer> i = set.iterator();
    String k= "";
    while (i.hasNext()) {
    int key = i.next();
    switch (key) {
    case 27: FINISH=false;break;
    case 38:k = k.concat(" Up");break;
    case 39:k = k.concat(" right");break;
    case 40:k = k.concat(" down");break;
    case 37:k = k.concat(" left");break;
    default :k = k.concat(" "+key);break;
    System.out.println(k);
    System.exit(0);
    public static void main(String[] args) {
    Handler handler = new Handler();
    JFrame frame = new JFrame();
    frame.setVisible(true);
    frame.addKeyListener(handler);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    handler.handle();
    @Override
    public void keyPressed(KeyEvent arg0) {
    synchronized (set) {
    set.add(arg0.getKeyCode());
    @Override
    public void keyReleased(KeyEvent arg0) {
    synchronized (set) {
    set.remove(arg0.getKeyCode());
    @Override
    public void keyTyped(KeyEvent arg0) {
    // TODO Auto-generated method stub
    // I 've got this code to handle keys. I am making an interface for a game and I would like to handle more than one key at same time. I want to handle the arrow keys. It seems to be fine except when I am holding down the Up arrow key i can hold just another key at same time.
    Example :
    Down Left Right - holding down left and right arrow key at same time
    Up left - with up arrow key i can hold just another one key. Not more.
    Can anybody help me to sort out this source?

    Thanks for your idea, very cool very useful
    [fresh fridays |http://reggae-cd.net/fresh-fridays-reggae-dance-in-jamaica]
    [passa passa DVD |http://reggae-dvd.com/passa-passa-reggae-music-and-dancing]
    [passa passa  |http://bestreggaemusic.com/passa-passa-90-mavado-fall-rain-fall-official-dance]
    [reggae videos|http://reggae-dancehall.net/crabb-up-friday-dancehall-reggae]

  • More then 5 key-presses?

    Hi there,
    I'm trying to re-create a game that me and my friends have been playing quite a lot in the last few weeks. The game is called Kurve, and it's an offline multiplayer game. Up to six players can play the game on one keyboard.
    The idea of the game is this:
    Each player get's a snake and two keys. The snake moves around and the player has to steer the snake around using these two keys and try to survive as long as possible, without colliding with other snakes.
    Now my problem:
    I've got the base engine working, snakes can move around with any key they want, collisions are beiging checked etc. But when doing some extra testing I noticed that, when I press 4 random keys on my keyboard, I couldn't press any other keys.
    This, however, is something that's important for the game and needs to be fixed if I'd ever want to release it.
    I'm currently doing keypresses in the folowing way:
    - implementing the KeyListener
    - storing each key-presssed-code in a HashSet
    - removing each key-released-code from the Hashset
    - whe excecuting a step; checking if the HashSet containt a steering key for a snake
    I hope I'm clear enough and that someone can help me.
    ~Sph
    Message was edited by:
    sph
    Message was edited by:
    sph

    I found a great page about this phenomenon a while back, unfortunately I've lost track of it. The basic problem you're having is that keyboards are not, in general, designed for gaming. They're designed for typing, which means the developers can cut corners to save some cash by making assumptions; mainly that you won't be pressing many keys at once. Aside from the metakeys (Ctrl,Shift,Alt), the keyboard is wired into one or more grids of keys. Each key within the grid activates both the horizontal and vertical wire underneath it, and with the two wires the grid can determine which key was pressed. Consider this small arrangement of keys:
    ||
    -AB-1
    -CD-2
    ||
    34Any individual key is easily identified, A=1&3, B=1&4, C=2&3, D=2&4. Two keys is a little trickier, but still doable. If A is held, B will activate 4, C will activate 2, and D will activate both 2 and 4. So we can still tell which two keys were pressed. At three keys, we have a problem. If A and D are pressed, all wires are already active, so pressing B or D won't accomplish anything. If, on the other hand, B is pressed, pressing either C or D will activate wire 2. This is more information, but still not enough. They keyboard can tell that either C or D was pressed, but not which. So any combination of two held keys and a third press either isn't be detected or is confusing, the keyboard can't tell what input it's getting. So it refuses to give any new output, except an error.
    I'm afraid you've hit one of the problems that's been annoying gamers for years. The only real solution is to either explore and find out what combos are OK on your keyboard, or try and find a manufacturer who makes a better one. In the latter case, you might look at someone who makes keyboards specifically for gamers, they're more likely to alow multiple presses (but check first!). You'll probably end up paying a premium for it, but you may decide that's worth it to you.
    -FM

  • DOWN Traversal out of JTextArea using SHIFT+ENTER key combination.

    Hi folks
    I slightly modified the focus-traversal code presented in Java Tutorial (http://java.sun.com/docs/books/tutorial/uiswing/misc/focus.html) to replace the CTRL+TAB combination with SHIFT-ENTER (because it is easier to type) but the code does not work. The code in the tutorial works for just ENTER key only. Am I making any mistake? Can anyone help me on this?
    Thanks in advance.
    Asif

    Thanks for your reply, Srinath. Following is the code (in hyphenated borders):
    =====================================================================
    Set forwardKeys = getFocusTraversalKeys(
    KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
    Set newForwardKeys = new HashSet(forwardKeys);
    newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_DOWN_MASK));
    setFocusTraversalKeys(KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS,
    newForwardKeys);
    =====================================================================
    Can you help me now? I would really appreciate it. Thanks
    Asif

  • Moowing focus with the tab key (swing)

    Hi. I have a JFrame with 4 text areas in. I want to be able to "hop" to the next text area by pressing the tab key. Most internet pages says this is default, but when I press tab, I get a tab space inside the text area I'm in.. Any ideas on how to do this? (i use Java 1.5)

    HashSet focusForward = new HashSet();
    HashSet focusBackward = new HashSet();
    focusForward.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,0));
    focusBackward.add(AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB,InputEvent.SHIFT_DOWN_MASK));
        myTextArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,focusForward);
    myTextArea.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,focusBackward);

  • Why am I getting == instead of equals() behaviour when I add to a HashSet?

    I want to maintain a set of ordered pairs. I have created a generic class OrderedPair<K,V>, and given it the following equals method:
        public boolean equals (OrderedPair<K,V> otherGuy) {
         return otherGuy != null && this.key.equals(otherGuy.key) && this.value.equals(otherGuy.value);
        }Now I want to create a set (say HashSet) of OrderedPairs of Strings that (obviously!) will not add a pair p if there is already a pair p1 in the set such that p.equals(p1).
        OrderedPair<String,String> p1 = mkPair ("tea", "biscuits");
        OrderedPair<String,String> p2 = mkPair ("tea", "biscuits");
        HashSet<OrderedPair<String,String>> s =  new HashSet<OrderedPair<String,String>>();
        s.add(p1);
        s.add(p1); // doesn't add a second copy
        s.add(p2) // now there are two pairs in the set, but they are "equal"If I add p1 or p2 multiple times, only the first attempt succeeds for each object tried, so the impl seems to be cheking reference identity rather than the equals method I so lovingly designed for OrderedPair.
    So what, conceptually, am I missing here?
    Thanks.
    -- Mike

    OK, thanks everyone. In hindsight, it's completely obvious, isn't it.
    So I've written the equals(Object) below in the naive way and I'm getting warnings about unsafe cast at line (a) and an unsafe assignemtn at line (b). I understand why this is a problem, but I'm not sure what the best solution is.
    How does one ask about instanceof for the otherObject, and how does one cast an Object to an OrderedPair<K,V> in a safe way?
        public boolean equals (Object otherObject) {
         if (otherObject == null || ! (otherObject instanceof OrderedPair<K,V>)) {    //line (a)
             return false;
         } else {
             OrderedPair<K,V> otherPair = (OrderedPair<K,V>) otherObject;      // line (b)
                return this.key.equals(otherPair.key)  && this.value.equals(otherPair.value);

  • Adding hashsets to a hashmap

    If I've created a hashmap of hashsets, for example,
    HashMap<String,HashSet<String>> hm = new HashMap<String,HashSet<String>> ();
    how do I add elements to a hashset at a particular key of the hashmap?

    I'm sure if you stop and think about it for a moment, it will come to you.

Maybe you are looking for