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.

Similar Messages

  • Keeps finding a "Object" not the real type.. I am really lost.. :D

    The calls to other objects work fine, I have testing all of them.. but! when I compile I get a error about finding a "object" type and not a String type at
    for(String blackStone : blackUnits.keySet())
                   if( getSetLib(blackStone) == 0 ) { removeSet.add(blackStone); }
             }   this is the whole class
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.HashSet;
    import java.util.Set;
    public class Stat
        private Token[][] board;
        private int bSize;
        private HashMap<String, HashSet> unitsWhite;
        private HashMap<String, HashSet> unitsBlack;
        double last;
        public Stat(Token[][] goBoard, int size)
            board = goBoard;
            bSize = size;
            unitsWhite = new HashMap< String , HashSet>();
            unitsBlack = new HashMap< String , HashSet>();
            last = bSize -1;
         * Delimiter is /
        public HashSet getLib(int x , int y)
            HashSet liberties = new HashSet<String>();
            //error catch
            if(board[x][y] == null){return liberties;}
            int tempX = x;
            int tempY = y;
            //error catch for out of rage if size ect..
            for(int i = 0 , liby = y ,libx = x ; i <= 3; i++)
                if(i == 0){libx = -1; liby = 0;}
                if(i == 1){libx = 0; liby = -1;}
                if(i == 2){libx = 1; liby = 0;}
                if(i == 3){libx = 0; liby = 1;}
                tempX = x+libx;
                tempY = y+liby;
                if(tempX >= 0 || tempY >= 0)
                    if( tempX <= last || tempY <= last )   
                         if( (tempX < 0 || tempY < 0) || ( tempX >= last || tempY >= last ) )
                           tempX = 0;
                           tempY = 0;
                         else
                            if( board[tempX][tempY] == null) { liberties.add(tempX+"/"+tempY); }
            return liberties;  
        public void getTer()
        public void checkForCaptured()
            Token black = null;
            Token white = null;
            HashMap blackUnits;
            HashMap whiteUnits; 
            HashSet removeSet ;
            removeSet = new HashSet<String>();
            //look for a Token on the board and if you find one look for any dead  Tokens
            //looks for a Token
            for(int x=0; x < bSize;x++)
              { for(int y=0 ; y < bSize   ;y++)
               { if(board[x][y] != null)
                   if (black == null)if( board[x][y].getColor().equals("black") ) black =  board[y][x];
                   if (white == null)if( board[x][y].getColor().equals("white") ) white =  board[y][x];
            System.out.println("this is black tokens color" +black.getColor());
            //looks for a dead unit
            if(black != null)
             { blackUnits = black.getUnits();
               System.out.println("black :" +blackUnits.keySet().size() ) ;
               for(String blackStone : blackUnits.keySet())
                   if( getSetLib(blackStone) == 0 ) { removeSet.add(blackStone); }
            if(white != null)
            { whiteUnits = white.getUnits();
                System.out.println(" white: "+whiteUnits.keySet().size() );
              for( String whiteStone : whiteUnits.keySet() )
               { if( getSetLib(whiteStone) == 0 ) { removeSet.add(whiteStone); } }
            board.removeUnitsSet(removeSet);    
         public int getSetLib(HashSet Units)
             return 0;
    }someone point me in the correct direction PLZ! I don't mind RTFM if you give me a FM and page/line to look at.
    THANKS!
    Message was edited by:
    monji112000

    The compiler doesn't know that you're only putting Strings in as keys. HashMap takes references to Object as keys and hence returns references to Object in keySet(). Note, however, that the object itself is still what you put in there. But the compiler only has the declared return type of the method to look at.
    // pre 1.5
    for (Iterator iter = set.iterator(); iter.hasNext();) {
        String key = (String)iter.next(); // cast Object to String. Only works if you actually put a String in
        // do stuff with key
    // 1.5, if you don't use generics
    for (Object obj : set) {
        String key = (String)obj;
        // do stuff with key
    // 1.5, with generics
    Set<String> set = ...;
    for (String key : set) {
        // do stuff with key
    }Since you have a Map, you'll have Map<String, SomeValueType>.
    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html
    http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf

  • Create command

    The Cashier class is responsible for processessing commands input by the user. There
    should be a single field, used to hold all the accounts that the cashier has created, which
    has the datatype HashMap. Remember that each entry added to a HashMap requires a key
    and a value. In this case, the key will be a String value which is the email address of the
    account. The value will be the Account object itself.
    You need to write a single constructor for Cashier which initialises the field to an empty
    HashMap
    import java.util.HashMap;
    public class Cashier
        HashMap<String, Accounts> userAccounts;
        Cashier()
            userAccounts = new HashMap<String, Accounts>();
    }I have created the single constructor for the HashMap, but I'm totally lost on the next step, any help will be appreciated:
    The next step is to make a command called create.
    The create command creates a new account. The cashier must ask for an email
    address and a password before constructing a new Account object and adding it
    to the HashMap of accounts. The cashier responds with ?Your account has been
    created?. If an account using the given email address already exists, the cashier
    responds with ?The account already exists?.

    Read about maps:
    http://java.sun.com/docs/books/tutorial/collections/index.html
    Especially:
    http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html
    http://java.sun.com/docs/books/tutorial/collections/implementations/map.html

  • Adding Objects To a HashSet, overriding equals and hashCode

    Hi everyone,
    I'm trying to add objects to a HashSet, using a string identifier (an attribute of these objects) to determine if two objects are equal.
    I have a class 'IntExpEvent' class that overrides the equals and hashCode methods.
    public class IntExpEvent implements ExperimentalEvent{
    public int correctAnswer;
    public String identifier;
    public IntExpEvent(String id, int correctAnswer){
         this.identifier = id;
         this.correctAnswer=correctAnswer;
    public String getID(){
         return(this.identifier);
    public boolean equals(ExperimentalEvent e){
         return (this.identifier.equals(e.getID()));
    public int hashCode(){
         System.out.println((this.getID()).hashCode());
         return (this.getID()).hashCode();
    private int hashCode=-1;
    public int hashCode() {
         if(hashCode==-1) {
         char[] ca=getID().toCharArray();
         for(int x=0;x<ca.length;x++) {
              hashCode+=ca[x];
         return(hashCode);
         IntExpEvent e1 = new IntExpEvent("test_IntExpEvent",4);
         IntExpEvent e2 = new IntExpEvent("test_IntExpEvent",6);
         HashSet hs = new HashSet();
         System.out.println(hs.add(e1));
         System.out.println(hs.add(e2));
    I can still add both e1 and e2 to the HashSet, which is what I'm trying to stop from happening. i.e. objects with the same identifier should be treated as the same object, allowing only one to be added to the HashSet. Does anyone know how I can do this? Help would be greatly appreciated

    In fact you don't override the equals method. The signature defined in the Object class is
      boolean equals(Object o)In your case it is
      boolean equals(ExperimentalEvent e)So instead of overriding the method you're overloading it.
    Regards

  • HashMap, HashSet and infinite loop

    hi,
    our code ended up in an infinite loop while parsing the entries of a HashMap with this code:
            Iterator it = myHashMap.entrySet().iterator();
            while (it.hasNext()) {
                field = (Map.Entry) it.next();
                // code that access content of "field"
            } as the loop creates some kind of objects, the JVM terminated with a out-of-memory. luckily we got a heap-dump file and that shows:
    - the hash-map has 325 entries
    - the loop was iterated more than 3 million times
    - the iterator "it" has a current and a next field pointing at the same element of the HashMap
    a snapshot of the heap-analysis of the iterator can be seen at
    http://www.sbox.tugraz.at/home/a/archmage/hashset/EntryIterator.html
    maybe the HashMap was accessed concurrently, but then there should be a ConcurrentModificationException.
    we are using
    > java -version
    java version "1.4.2_12"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_12-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_12-b03, mixed mode)for me, this looks like a JVM bug, but i cannot really believe that (and i could not find a bug stating this behaviour).
    is there anything i did not notice during using hashmaps/hashsets/iterators?
    regards, werner

    there should be aConcurrentModificationException.
    Not necessarily. The iterators cannot always detectConcurrentModificationException.
    api-docs of HashMap say:
    A structural modification is any operation that adds
    or deletes one or more mappings
    if the map is structurally modified at any time after
    the iterator is created, in any way except through
    the iterator's own remove or add methods, the
    iterator will throw a
    ConcurrentModificationException.
    for me, that means, the iterator should detect any
    "add" or "delete" operation like map.put(...). am i
    wrong? or are the docs wrong here?Immediately AFTER the paragraph you quoted, it says
    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html
    Furthermore, did you READ what I said after that?
    It's FAR MORE LIKELY to be a result of data corruption, rather than multiple simultaneous iterators.

  • Convert HashMap to HashSet for @OneToMany for JPA Hibernate Implementation

    Hi,
    I have a HashMap with @OneToMany relationship as shown below:-
    @Entity
    Class CustomerDetails {
      @OneToMany(fetch = FetchType.EAGER)
      @JoinTable(name="Cust_Order")
      @MapKeyColumn(name="orders_number")
       public Map<String,Order> getOrders() { return orders; }
       public void setOrders(Map<String,Order> orders) { this.orders = orders; }
       private Map<String,Order> orders;
       // getters & setters for orders
    This class does have "N" number of @OneToMany relationships which is represented as "HashMap" and I want all of them to be eagerly loaded.Where it throws HibernateException "Cannot simultaneously fetch Multiple Bags" this is due to multiple collections in CustomerDetails
    with fetchType as "EAGER". Now I want to convert my collection type from HashMap to HashSet so that I can resolve this problem? Please let me know how I can convert HashMap to HashSet as HashMap takes key,value pairs unlike HashSet?
    private Map<String,Order> orders;
    to
    private Set<Order> orders;
    Please clarify the above & is there any better way to do it?
    Thanks.

    Hello,
    I'm not sure exactly what you mean, but there is no problem using eager or lazy access types with either HashMap or HashSets in EclipseLink/TopLink.  As a HashSet is a Set implementation, it is nothing like a Map and cannot be used as a HashMap replacement that I'm aware of.   The code you posted will work with EclipseLink without exceptions being thrown.
    If you have a Hibernate specific problem, you might try posting on that Hibernate's forum for an answer.

  • HashSet - Adding Integer values - Error Class Excpetion Help

    I am trying to add integers into the HashSet it is not allowing me to add it? does it mean that I cannot add integers. I also tried using the Integer class to input the values, still getting the same error. The Error is in the line : ts.add(3);
    Any thoughts why such an error ?
    The error that I get is :
    java TreeTest
    Exception in thread "main" java.lang.ClassCastException: java.lang.String
    at java.lang.Integer.compareTo(Integer.java:35)
    at java.util.TreeMap.compare(TreeMap.java:1093)
    at java.util.TreeMap.put(TreeMap.java:465)
    at java.util.TreeSet.add(TreeSet.java:210)
    at TreeTest.main(TreeTest.java:12)
    PK
    import java.util.*;
    class TreeTest
         public static void main(String[] args)
              TreeSet ts = new TreeSet();
              ts.add("Z");
              ts.add("A");
              ts.add("P");
              ts.add(3);
              ts.add(new Integer(1));
              ts.add(new Integer(7));
              System.out.println("The size is \t" + ts.size());
    }

    hii,
    In the TreeSet the elements you add should be of same class type.
    otherwise it can't do the sorting process.can u sort alphabets and numeric together? if u are adding Integer type only add int values or objs.if u want to add String add that n String objs.
    try the following code
    import java.util.*;
    class TreeTest
         public static void main(String[] args)
              try
              TreeSet ts = new TreeSet();
              int a=3;
              //ts.add("Z");
              //ts.add("A");
              //ts.add("P");
              ts.add(new Integer(7));
              ts.add(new Integer(1));
              ts.add(a);
              System.out.println("The size is \t" + ts.size());     
              catch (Exception e)
                   System.out.println(e);     
    }

  • Implementing HashMap using HashSet

    Hi I need to implement a HashMap using a HashSet it extends AbstractMap. Can you guys tell me if I am on a right PAGE.
    package pa2;
    import java.util.AbstractMap;
    import java.util.Set;
    import java.util.Map;
    public class HashMap1 extends AbstractMap
        Map map;
        public HashMap1(HashSet set)
            map = (Map)set;
    /code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Yes I belive thats what I am doing except I get this:
    Exception in thread "main" java.util.ConcurrentModificationException
         at pa2.HashSet$HashSetIterator.hasNext(HashSet.java:164)
         at pa2.HashMap1.remove(HashMap1.java:87)
         at pa2.TestMap1.test(TestMap1.java:21)
         at pa2.TestMap1.main(TestMap1.java:34)And here's some of my code:
    package pa2;
    import java.util.AbstractMap;
    import java.util.Map;
    import java.util.Set;
    import java.util.Iterator;
    * Hash table implementation of the Map.
    public class HashMap1
        extends AbstractMap
      Set set;
       * Construct an empty HashMap.
      public HashMap1()
        super();
        set = makeEmptyKeySet();
      public void clear()
        set.clear();
      public boolean containsKey(Object key)
        Iterator itr = set.iterator();
        while(itr.hasNext()){
          Pair p = (Pair)itr.next();
          if(((String)(p.getKey())).compareTo((String)key) == 0){
            return true;
        return false;
      public boolean containsValue(Object value)
        Iterator itr = set.iterator();
        while(itr.hasNext()){
          Pair p = (Pair)itr.next();
          if(((String)(p.getValue())).compareTo((String)value) == 0){
            return true;
        return false;
      public Object get(Object key)
        Iterator itr = set.iterator();
        while(itr.hasNext()){
          Pair o = (Pair)itr.next();
          String ob = (String)o.getKey();
          if(ob.compareTo((String)key) == 0){
            return o;
        return null;
      public Object put(Object key, Object value)
        set.add(makePair(key, value));
        return null;
      public void putAll(Map t)
        Iterator itr = t.entrySet().iterator();
        while(itr.hasNext()){
          put((String)(((Pair)itr.next()).getKey()),
              (String)(((Pair)itr.next()).getValue()));
      public Object remove(Object key)
        String value = null;
        Iterator itr = set.iterator();
        while(itr.hasNext()){
          Pair p = (Pair)itr.next();
          String sp = (String)p.getKey();
          if(sp.compareTo((String)key) == 0){
            value = (String)p.getValue();
            set.remove(makePair(key, value));
        return null;
    }

  • Adding parentheses to each item in HashSet

    Dear All,
    Having almost completed my first java tool which queries a database to allow user-defined filtering, I'm running into a last 'small' problem:
    I won't bore you guys with the whole thing, but instead will just focus on the part where i'm stuck, in the hope that somebody can give me a useful tip as to how to solve this! Thanks very much in advance for any input!
    Basically, what it comes down to is that I query the database twice, resulting in two lists of data stored as HashSets in Java, to then work out the intersect of them both with the listI.retainAll(listII) function. Finally, I want to use the merged list to query the database again, using the variables listed in the final set. In order to use the list in the query, I first convert the HashSet to a string as follows:
    String convList = listI.toString();As this results in a string with square brackets [] and mySQL needs regular brackets, I convert them like this:
    convList = convList.replace('[', '(');
    convList = convList.replace(']', ')');This will result in something along the lines as (result1, result2, result3, result4, etc.). The problem is though, that I would need it to be like
    ("result1", "result2", "result3", "result4") in order for mySQL to accept it using the IN clause.
    I tried to add the parentheses using:
    convList = convList.replaceAll(',', '",');
            convList = convList.replaceAll(' ', ' "');but the Java compiler complains of an error with "unclosed character literal", so I was hoping somebody could maybe give me a hint as to how I can add parentheses for each member in the list? Thanks alot in advance

    les_paulde wrote:
    wow, thanks for your swift reply! This definitely solved my problem and I can now run the query. The code turned out as follows:
    String convList = listI.toString();
    convList = convList.replace("[", "(\"");
    convList = convList.replace("]", "\")");
    convList = convList.replaceAll(",", "\",");
    convList = convList.replaceAll(" ", " \"");
    And what happens if the String representation of the object in your list contains one of the characters you're replacing? It will go awfully wrong!
    This is safer:
    public static String asString(List<?> list) {
        StringBuilder b = new StringBuilder();
        b.append('(');
        for(int i = 0; i < list.size(); i++) {
            b.append('"').append(list.get(i)).append('"');
            if(i < list.size()-1) b.append(", ");
        return b.append(')').toString();
    System.out.println(asString(listI));

  • Object lost once added to another set

    Hi,
    I have the following objects in my class
    public static HashSet<Integer> illegalIndexes;
    public static Map<OWLObject, Set<Integer>> activeRoleIndexes;
    assume I do the following;
    Integer i= 10;
    Set<Integer> roleIndexes = new HashSet<Integer>();
    roleIndexes.add(i);
    activeRoleIndexes.put(role,roleIndexes);
    if later i is added to illegalIndexes, it disappears from the set within the HashMap activeRoleIndexes....
    Any ideas why this could happen? or how to solve it?

    809467 wrote:
    if later i is added to illegalIndexes, it disappears from the set within the HashMap activeRoleIndexes....
    Any ideas why this could happen? or how to solve it?Impossible to say without more code. Only way I could imagine it disappear would be if you recreated activeRoleIndexes or if you passed around your roleIndexes set and removed it yourself.
    Or maybe you're using the same roleIndexes for all your roles, instead of creating each role their own instance. Depends on your other code.

  • Class HashSet and hashCode method

    I'm using a HashSet class with elements of class A.
    I define the equals method but when i add a object which is already in the set, this object is duplicate.
    Do i have to define the hashCode method in the class A? If yes, i don't understand why this method is used when adding a object.
    Can you give me a explanation ?

    Yes, you do. The hashCode method is used by HashSet and HashMap to find an object. See the API doc for Object, which explains the relationship between equals and hashCode.

  • TableSorter errors when adding new data

    so here is the deal:
    I am using the TableSorter.java helper class with DefaultTableModel
    from: http://java.sun.com/docs/books/tutorial/uiswing/components/table.html
    It works great when the data is static and I get it for the first time. however, occationally, when adding new data I get a NullPointerException error.
    in use:
    DefaultTableModel.addRow()
    DefaultTableModel.removeRow() and
    DefaultTableModel.insertRow() methods.
    Error:
    java.lang.ArrayIndexOutOfBoundsException: 5
         at com.shared.model.TableSorter.modelIndex(TableSorter.java:294)
         at com.shared.model.TableSorter.getValueAt(TableSorter.java:340)
         at javax.swing.JTable.getValueAt(Unknown Source)
         at javax.swing.JTable.prepareRenderer(Unknown Source)...
    code problem I:
        public Object getValueAt(int row, int column)
            return tableModel.getValueAt(modelIndex(row), column);
        }code problem II:
        public int modelIndex(int viewIndex)
                 return getViewToModel()[viewIndex].modelIndex;     
        }TableSroter class:
    package com.shared.model;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.util.List;
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.*;
    * TableSorter is a decorator for TableModels; adding sorting
    * functionality to a supplied TableModel. TableSorter does
    * not store or copy the data in its TableModel; instead it maintains
    * a map from the row indexes of the view to the row indexes of the
    * model. As requests are made of the sorter (like getValueAt(row, col))
    * they are passed to the underlying model after the row numbers
    * have been translated via the internal mapping array. This way,
    * the TableSorter appears to hold another copy of the table
    * with the rows in a different order.
    * <p/>
    * TableSorter registers itself as a listener to the underlying model,
    * just as the JTable itself would. Events recieved from the model
    * are examined, sometimes manipulated (typically widened), and then
    * passed on to the TableSorter's listeners (typically the JTable).
    * If a change to the model has invalidated the order of TableSorter's
    * rows, a note of this is made and the sorter will resort the
    * rows the next time a value is requested.
    * <p/>
    * When the tableHeader property is set, either by using the
    * setTableHeader() method or the two argument constructor, the
    * table header may be used as a complete UI for TableSorter.
    * The default renderer of the tableHeader is decorated with a renderer
    * that indicates the sorting status of each column. In addition,
    * a mouse listener is installed with the following behavior:
    * <ul>
    * <li>
    * Mouse-click: Clears the sorting status of all other columns
    * and advances the sorting status of that column through three
    * values: {NOT_SORTED, ASCENDING, DESCENDING} (then back to
    * NOT_SORTED again).
    * <li>
    * SHIFT-mouse-click: Clears the sorting status of all other columns
    * and cycles the sorting status of the column through the same
    * three values, in the opposite order: {NOT_SORTED, DESCENDING, ASCENDING}.
    * <li>
    * CONTROL-mouse-click and CONTROL-SHIFT-mouse-click: as above except
    * that the changes to the column do not cancel the statuses of columns
    * that are already sorting - giving a way to initiate a compound
    * sort.
    * </ul>
    * <p/>
    * This is a long overdue rewrite of a class of the same name that
    * first appeared in the swing table demos in 1997.
    * @author Philip Milne
    * @author Brendon McLean
    * @author Dan van Enckevort
    * @author Parwinder Sekhon
    * @version 2.0 02/27/04
    public class TableSorter extends AbstractTableModel
        protected TableModel tableModel;
        public static final int DESCENDING = -1;
        public static final int NOT_SORTED = 0;
        public static final int ASCENDING = 1;
        private static Directive EMPTY_DIRECTIVE = new Directive(-1, NOT_SORTED);
        public static final Comparator COMPARABLE_COMAPRATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return ((Comparable) o1).compareTo(o2);
        public static final Comparator LEXICAL_COMPARATOR = new Comparator()
            public int compare(Object o1, Object o2)
                return o1.toString().compareTo(o2.toString());
        private Row[] viewToModel;
        private int[] modelToView;
        private JTableHeader tableHeader;
        private MouseListener mouseListener;
        private TableModelListener tableModelListener;
        private Map columnComparators = new HashMap();
        private List sortingColumns = new ArrayList();
        public TableSorter()
            this.mouseListener = new MouseHandler();
            this.tableModelListener = new TableModelHandler();
        public TableSorter(TableModel tableModel)
            this();
            setTableModel(tableModel);
        public TableSorter(TableModel tableModel, JTableHeader tableHeader)
            this();
            setTableHeader(tableHeader);
            setTableModel(tableModel);
        private void clearSortingState()
            viewToModel = null;
            modelToView = null;
        public TableModel getTableModel()
            return tableModel;
        public void setTableModel(TableModel tableModel)
            if (this.tableModel != null)
                this.tableModel.removeTableModelListener(tableModelListener);
            this.tableModel = tableModel;
            if (this.tableModel != null)
                this.tableModel.addTableModelListener(tableModelListener);
            clearSortingState();
            fireTableStructureChanged();
        public JTableHeader getTableHeader()
            return tableHeader;
        public void setTableHeader(JTableHeader tableHeader)
            if (this.tableHeader != null)
                this.tableHeader.removeMouseListener(mouseListener);
                TableCellRenderer defaultRenderer = this.tableHeader.getDefaultRenderer();
                if (defaultRenderer instanceof SortableHeaderRenderer)
                    this.tableHeader.setDefaultRenderer(((SortableHeaderRenderer) defaultRenderer).tableCellRenderer);
            this.tableHeader = tableHeader;
            if (this.tableHeader != null)
                this.tableHeader.addMouseListener(mouseListener);
                this.tableHeader.setDefaultRenderer
                        new SortableHeaderRenderer(this.tableHeader.getDefaultRenderer())
        public boolean isSorting()
            return sortingColumns.size() != 0;
        private Directive getDirective(int column)
            for (int i = 0; i < sortingColumns.size(); i++)
                Directive directive = (Directive)sortingColumns.get(i);
                if (directive.column == column)
                    return directive;
            return EMPTY_DIRECTIVE;
        public int getSortingStatus(int column)
            return getDirective(column).direction;
        private void sortingStatusChanged()
            clearSortingState();
            fireTableDataChanged();
            if (tableHeader != null)
                tableHeader.repaint();
        public void setSortingStatus(int column, int status)
            Directive directive = getDirective(column);
            if (directive != EMPTY_DIRECTIVE)
                sortingColumns.remove(directive);
            if (status != NOT_SORTED)
                sortingColumns.add(new Directive(column, status));
            sortingStatusChanged();
        protected Icon getHeaderRendererIcon(int column, int size)
            Directive directive = getDirective(column);
            if (directive == EMPTY_DIRECTIVE)
                return null;
            return new Arrow(directive.direction == DESCENDING, size, sortingColumns.indexOf(directive));
        private void cancelSorting()
            sortingColumns.clear();
            sortingStatusChanged();
        public void setColumnComparator(Class type, Comparator comparator)
            if (comparator == null)
                columnComparators.remove(type);
            else
                columnComparators.put(type, comparator);
        protected Comparator getComparator(int column)
            Class columnType = tableModel.getColumnClass(column);
            Comparator comparator = (Comparator) columnComparators.get(columnType);
            if (comparator != null)
                return comparator;
            if (Comparable.class.isAssignableFrom(columnType))
                return COMPARABLE_COMAPRATOR;
            return LEXICAL_COMPARATOR;
        private Row[] getViewToModel()
            if (viewToModel == null)
                int tableModelRowCount = tableModel.getRowCount();
                viewToModel = new Row[tableModelRowCount];
                for (int row = 0; row < tableModelRowCount; row++)
                    viewToModel[row] = new Row(row);
                if (isSorting())
                    Arrays.sort(viewToModel);
            return viewToModel;
        public int modelIndex(int viewIndex)
                 return getViewToModel()[viewIndex].modelIndex;     
        private int[] getModelToView()
            if (modelToView == null)
                int n = getViewToModel().length;
                modelToView = new int[n];
                for (int i = 0; i < n; i++)
                    modelToView[modelIndex(i)] = i;
            return modelToView;
        // TableModel interface methods
        public int getRowCount()
            return (tableModel == null) ? 0 : tableModel.getRowCount();
        public int getColumnCount()
            return (tableModel == null) ? 0 : tableModel.getColumnCount();
        public String getColumnName(int column)
            return tableModel.getColumnName(column);
        public Class getColumnClass(int column)
            return tableModel.getColumnClass(column);
        public boolean isCellEditable(int row, int column)
            return tableModel.isCellEditable(modelIndex(row), column);
        public Object getValueAt(int row, int column)
            return tableModel.getValueAt(modelIndex(row), column);
        public void setValueAt(Object aValue, int row, int column)
            tableModel.setValueAt(aValue, modelIndex(row), column);
        // Helper classes
        private class Row implements Comparable
            private int modelIndex;
            public Row(int index)
                this.modelIndex = index;
            public int compareTo(Object o)
                int row1 = modelIndex;
                int row2 = ((Row) o).modelIndex;
                for (Iterator it = sortingColumns.iterator(); it.hasNext();)
                    Directive directive = (Directive) it.next();
                    int column = directive.column;
                    Object o1 = tableModel.getValueAt(row1, column);
                    Object o2 = tableModel.getValueAt(row2, column);
                    int comparison = 0;
                    // Define null less than everything, except null.
                    if (o1 == null && o2 == null)
                        comparison = 0;
                    } else if (o1 == null)
                        comparison = -1;
                    } else if (o2 == null)
                        comparison = 1;
                    } else {
                        comparison = getComparator(column).compare(o1, o2);
                    if (comparison != 0)
                        return directive.direction == DESCENDING ? -comparison : comparison;
                return 0;
        private class TableModelHandler implements TableModelListener
            public void tableChanged(TableModelEvent e)
                // If we're not sorting by anything, just pass the event along.            
                if (!isSorting())
                    clearSortingState();
                    fireTableChanged(e);
                    return;
                // If the table structure has changed, cancel the sorting; the            
                // sorting columns may have been either moved or deleted from            
                // the model.
                if (e.getFirstRow() == TableModelEvent.HEADER_ROW)
                    cancelSorting();
                    fireTableChanged(e);
                    return;
                // We can map a cell event through to the view without widening            
                // when the following conditions apply:
                // a) all the changes are on one row (e.getFirstRow() == e.getLastRow()) and,
                // b) all the changes are in one column (column != TableModelEvent.ALL_COLUMNS) and,
                // c) we are not sorting on that column (getSortingStatus(column) == NOT_SORTED) and,
                // d) a reverse lookup will not trigger a sort (modelToView != null)
                // Note: INSERT and DELETE events fail this test as they have column == ALL_COLUMNS.
                // The last check, for (modelToView != null) is to see if modelToView
                // is already allocated. If we don't do this check; sorting can become
                // a performance bottleneck for applications where cells 
                // change rapidly in different parts of the table. If cells
                // change alternately in the sorting column and then outside of            
                // it this class can end up re-sorting on alternate cell updates -
                // which can be a performance problem for large tables. The last
                // clause avoids this problem.
                int column = e.getColumn();
                if (e.getFirstRow() == e.getLastRow()
                        && column != TableModelEvent.ALL_COLUMNS
                        && getSortingStatus(column) == NOT_SORTED
                        && modelToView != null)
                    int viewIndex = getModelToView()[e.getFirstRow()];
                    fireTableChanged(new TableModelEvent(TableSorter.this,
                                                         viewIndex, viewIndex,
                                                         column, e.getType()));
                    return;
                // Something has happened to the data that may have invalidated the row order.
                clearSortingState();
                fireTableDataChanged();
                return;
        private class MouseHandler extends MouseAdapter
            public void mouseClicked(MouseEvent e)
                JTableHeader h = (JTableHeader) e.getSource();
                TableColumnModel columnModel = h.getColumnModel();
                int viewColumn = columnModel.getColumnIndexAtX(e.getX());
                int column = columnModel.getColumn(viewColumn).getModelIndex();
                if (column != -1)
                    int status = getSortingStatus(column);
                    if (!e.isControlDown())
                        cancelSorting();
                    // Cycle the sorting states through {NOT_SORTED, ASCENDING, DESCENDING} or
                    // {NOT_SORTED, DESCENDING, ASCENDING} depending on whether shift is pressed.
                    status = status + (e.isShiftDown() ? -1 : 1);
                    status = (status + 4) % 3 - 1; // signed mod, returning {-1, 0, 1}
                    setSortingStatus(column, status);
        private static class Arrow implements Icon
            private boolean descending;
            private int size;
            private int priority;
            public Arrow(boolean descending, int size, int priority)
                this.descending = descending;
                this.size = size;
                this.priority = priority;
            public void paintIcon(Component c, Graphics g, int x, int y)
                Color color = c == null ? Color.GRAY : c.getBackground();            
                // In a compound sort, make each succesive triangle 20%
                // smaller than the previous one.
                int dx = (int)(size/2*Math.pow(0.8, priority));
                int dy = descending ? dx : -dx;
                // Align icon (roughly) with font baseline.
                y = y + 5*size/6 + (descending ? -dy : 0);
                int shift = descending ? 1 : -1;
                g.translate(x, y);
                // Right diagonal.
                g.setColor(color.darker());
                g.drawLine(dx / 2, dy, 0, 0);
                g.drawLine(dx / 2, dy + shift, 0, shift);
                // Left diagonal.
                g.setColor(color.brighter());
                g.drawLine(dx / 2, dy, dx, 0);
                g.drawLine(dx / 2, dy + shift, dx, shift);
                // Horizontal line.
                if (descending) {
                    g.setColor(color.darker().darker());
                } else {
                    g.setColor(color.brighter().brighter());
                g.drawLine(dx, 0, 0, 0);
                g.setColor(color);
                g.translate(-x, -y);
            public int getIconWidth()
                return size;
            public int getIconHeight()
                return size;
        private class SortableHeaderRenderer implements TableCellRenderer
            private TableCellRenderer tableCellRenderer;
            public SortableHeaderRenderer(TableCellRenderer tableCellRenderer)
                this.tableCellRenderer = tableCellRenderer;
            public Component getTableCellRendererComponent(JTable table,
                                                           Object value,
                                                           boolean isSelected,
                                                           boolean hasFocus,
                                                           int row,
                                                           int column)
                Component c = tableCellRenderer.getTableCellRendererComponent(table,
                        value, isSelected, hasFocus, row, column);
                if (c instanceof JLabel) {
                    JLabel l = (JLabel) c;
                    l.setHorizontalTextPosition(JLabel.LEFT);
                    int modelColumn = table.convertColumnIndexToModel(column);
                    l.setIcon(getHeaderRendererIcon(modelColumn, l.getFont().getSize()));
                return c;
        private static class Directive
            private int column;
            private int direction;
            public Directive(int column, int direction)
                this.column = column;
                this.direction = direction;
    }any input will be appreciated.
    thanks
    Peter

    The code you posted doesn't help us at all. Its just a duplicate of the code from the tutorial. The custom code is what you have written. For example do you update the TableModel from the Event Thread? Do you update the SortModel or the DefaultTableModel? If you actually provide your test code and somebody has already downloaded the sort classes, then maybe they will test your code against the classes. But I doubt if people will download the sort classes and create a test program just to see if they can duplicate your results (at least I know I'm not about to).

  • Reading HashMap Values From a File

    Hi,
    I haven't done file I/O in quite a while, so I'm a little rusty.
    I have a HashMap<TreePath, Entity> that I need to store persistently. Thus far I have been creating a new HashMap every time a new session starts and populating it with Entity objects that I create from JDBC ResultSets. The TreePath is generated by adding each Entity object to its parent in the JTree. That all works well.
    Now I'm trying to write the HashMap to file using ObjectOutputStream. Basically I want to be able to load the JTree (which does not need to be persistent at this stage), and as I load it I get the TreePath of each TreeNode. If that TreePath is a key in the persistent HashMap, then I want to display the details stored in the corresponding Entity. However, when I try to read the HashMap using an ObjectInputStream, I get a NullPointer.
    I'm not sure whether the problem is in the way I'm trying to write or read the HashMap, or both. I've followed the examples in the API but they don't seem to be doing the job.
    Any suggestions?

    I have isolated the problem.
    HashMap<TreePath, Entity> map = memory.getMap();
    TreePath nodePath = new TreePath(node.getPath()); //where node is a DefaultMutableTreeNode
    System.out.println("1. Desired key is: " + nodePath);
    System.out.println("2. Map contains key: " + map.containsKey(nodePath));
    System.out.println("3. Keys in map: " + map.keySet().toString());When I use a volatile Java object to store the map, an example of the output produced by the following code is:
    1. Desired key is: [DW, Acct]
    2. Map contains key: true
    3. Keys in map: [[DW], [DW, Acct]]
    However, when I use file I/O to make the Java object permanent, an example of the output produced by the following code is:
    1. Desired key is: [DW, Acct]
    2. Map contains key: false
    3. Keys in map: [[DW], [DW, Acct]]
    As far as I can see, line 2 of the I/O output should be true, not false, since line 3 shows that the key is present in the map.
    Am I missing something here, or is the containsKey() method returning the incorrect result? It looks like it is getting its reference to map all wrong.

  • Multiple query results in HashMap

    Hi,
    Can anybody tell me how I can store multiple results of a select query in a HashMap. I basically know how to do it but here is the problem:
    I want the table ids to be the keys and ArraySets containing database data to be the values of the HashMap. But whenever I add a new key/value pair to the HashMap all the values get overridden with the ArraySet I add.
    Here is my code:
    public HashMap getResults() throws Exception {
    Class.forName(org.gjt.mm.mysql.Driver);
    Connection con = DriverManager.getConnection(jdbc:mysql:///myDbName?user=user&password=password);
    HashMap hmResults = new HashMap();
    ArrayList alValues = new ArrayList();
    PreparedStatement preparedStatement = con.prepareStatement("select id, name, email from mytable");
    ResultSet resultSet = preparedStatement.executeQuery();
    if (resultSet != null) {
    while (resultSet.next()) {
    alValues.clear();
    alValues.add(resultSet.getString("id"));
    alValues.add(resultSet.getString("name"));
    alValues.add(resultSet.getString("email"));
    // the next line adds the correct key and value but also overrides all the other values in the HashMap, why?
    hmResults.put(resultSet.getString("id"), alValues);
    return(hmResults);
    The method above returns a HashMap containing the correct keys but the values are all the same.
    What am I doing wrong?
    Thanks for helping me out!

    Because your adding to the HashMap a reference to that ArrayList, not the ArrayList itself. So basically each key in your HashMap references the one ArrayList, which you repeatedly clear and update. In the end, all your keys map to the same reference, which will contain the very last information retrieved from the ResultSet.
    Simple fix... place the ArrayList alValues = new ArrayList() line inside your loop, and each key will be mapped to a different reference.

  • How to get a list corresponding to each key in hashmap

    hi all
    in hash map we can put key value pairs ... but what if i want to get a list of values coresponding to each unique key ..
    ... can we do it by storing a list Object corresponding each key in a HashMap ... is this the best way out ??
    For example in a chat server ... i want to mainitain a list of users corresponding to each room (the key ) in a HashMAp .. so the corresponding operations would be adding and deleting users as and when they login / logout .. getting a list of alll users in a particular room .. etc

    Actually i am looking forward for something like
    I may b wrong in syntax .. just doing it to give you a clear picture...
    HashMap h = new HashMap();
    // now suppose chat rooms are "billing","faq"
    //adding users for room billing
    h.add("billing","John");
    h.add("billing","Mr. A");
    h.add("billing","Mr. B");
    //adding for room faq
    h.add("faq","Mr. C");
    h.add("faq","Mr. D");
    // now i want all users of billing
    List l = h.get("billing");                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

Maybe you are looking for