HashCode on implementation of Set
javadoc on Set<E> hashcode:
"int hashCode()
"Returns the hash code value for this set. The hash code of a set is defined to be the sum of the hash codes of the elements in the set, where the hashcode of a null element is defined to be zero. This ensures that s1.equals(s2) implies that s1.hashCode()==s2.hashCode() for any two sets s1 and s2, as required by the general contract of the Object.hashCode method."
Let's say I have a class Foo which is an implementation of Set<Bar>. Bar's hashCode is a perfect hash. But the sum of such hash codes won't be a perfect hash on Foo instances, and I'd like to have Foo's hashCode return a perfect hash. (A perfect hash is possible given the domain of Bar instances). If Foo's hashCode returns a value which meets the assurance stated in the doc, but is not the sum of the element hash codes, do I cause a potential client problem by violating what the hash code is "defined to be"?
In addition to the excelent advice jverd gave I'd
like to ask if beeing a Set<Bar> is Foo's primary
job. Do clients view it as anything else, than a
Set<Bar>? (If it's usually referenced from a
variabled delcard "Foo foo;" and not "Set<Bar> foo",
then chances are, that beeing a Set is not it's
primary job).Yes, being a Set<Bar> is its primary, and probably only, job. The name of the class is (the equivalent of) BarSet.
>
If indeed Foo "is" "not just" a Set<Bar>, then you
might want to remove that interface from it and
produce a delegate, that acts as the Set.
(foo.getSet())
This way you could implement hashCode() of Foo the
perfect way you want it to and have
foo.getSet().hashCode() follow the requirements laid
out by Set.hashCode()).
This way you could fullfill both requirements.Or, as kajbj implies, I could fulfill both by just supplying a perfectHashCode(). I like that idea.
Message was edited by:
com.stevebrecher to correct misspelling of a name
Similar Messages
-
Could someone please show me an example of how to implement the Set Class?
Here's the code for the class:
* @(#)Set.java
package ds.util;
import java.util.*;
* A set is a collection that contains no duplicate elements; that is, sets contain
* no pair of elements obj1 and obj2 such that obj1.equals(obj2). As implied by
* its name, this interface models the mathematical <i>set</i> abstraction.<p>
* The <tt>Set</tt> interface extends the <tt>Collection</tt> interface and
* places additional specification on the <tt>add</tt> method.
public interface Set<T> extends Collection<T>
* Returns the number of elements in this set.
* @return the number of elements in this set.
int size();
* Returns <tt>true</tt> if this set contains no elements.
* @return <tt>true</tt> if this set contains no elements.
boolean isEmpty();
* Returns <tt>true</tt> if this set contains the specified element.
* @param item element whose presence in this set is to be tested.
* @return <tt>true</tt> if this set contains the specified element.
boolean contains(Object item);
* Returns an iterator over the elements in this set.
* @return an <tt>Iterator</tt> positioned at an element in the set..
Iterator<T> iterator();
* Returns an array containing all of the elements in this set.
* @return an array containing all of the elements in this set.
Object[] toArray();
// Modification Operations
* Adds the specified element to this set if it is not already present.
* If this set already contains the specified element, the call leaves
* this set unchanged and returns <tt>false</tt>.
* @param item element to be added to this set.
* @return <tt>true</tt> if this set did not already contain the specified
* element.
boolean add(T item);
* Removes the specified element from this set if it is present. Returns
* <tt>true</tt> if the set contained the specified element.
* @param item object to be removed from this set, if present.
* @return true if the set contained the specified element.
boolean remove(Object item);
* Removes all of the elements from this set. This set will be empty after
* this call returns.
void clear();
}What specific trouble are you having?
If we "show you an example of how to implement a Set," we're doing your homework for you. Most here won't do that, and with good reason. -
Implement extendable set of constants
Hi!
I am trying to figure out what would be a suitable way of implementing a set of default constants that should be possible to extend with custom ones. I am creating an API that will have several sets of constant values but the user of the API should be able to extend/register/add additional constants to these sets. In my first attempt I have been looking at the enum type but its not straight forward to use enums since they cannot be extended. One solution that I discovered elsewhere was to define an interface for the constants and let the enum implement that interface. However I am not really sure I understand how this should look.
It would be great with some code examples on the enum solution mentioned above. Other suggestions are also appreciated!Encephalopathic, thats a good question.
I guess it is because they actually are constants in the API and I want the user to treat them as constants.What do you mean in the part I underlined?
There are lots of ways to prevent the user to change a reference (the surest one being not to expose it at all, more on that later).
Moreover the user should have easy access to the values (like Substance.PO4).Which your DefaultSubstance attempt above achieves.
I also want to prevent multiple instances of the same value (substance).Can you elaborate why?
Often this "need" to have only one instance is overrated (if not plain wrong). For the occasions where it is valid (and countless discussions on whether it is or isn't), you can look at the Singleton design pattern, and the (unofficial name but easily derived) multiton variant.
Let's say that I implement a simple Substance class and then a DefaultSubstances class that defines the default set of values:Fine sketch.
It feels like I do not have enough control when the user subclass this class to implement new constants.Which kind of "control" do you want?
Most of what I can imagine can be achieved by doing checks in the constructor of a root superclass, e.g. Substance (if a user subclasses the class, the compiler/JVM will make sure his constructor invokes yours). e.g. if you want to make sure no-one redefines a substance named "PO4" that's easily done in the superclass' constructor.
And how do I make this class and all subclasses iterable over all defined constants?The root superclass can maintain a private static map of all known substances, populated by the constructor.
Remember the point about not exposing the reference? Well the root superclass could expose the known substances via a method call:
Substance po4 = Substance.get("PO4");
Perhaps it would be a good soultion to give up the enum classNot necessarily. But you sure can't extend enums, so you'd have to define an interface, as Joachim demonstrated; but with an interface you don't have the "veto" power of a mandatory superconstructor.
In general: can you elaborate on what the Substance class does? Which methods does it expose (you know enums can expose methods)?
How is it used (e.g. switch statements).
It is also possible that the code might be refactored into something completely different, leveraging polymorphism instead of if/switch based on constants, but that depends on the usage.
Edited by: jduprez on Mar 1, 2010 12:18 PM -
HashCode() method implementation in KVM
hi, I've got a problem with the KVM implementation of Object.
More specifically I verified that Class Objects change their hash codes during a run session of the same VM which seems to be a violation of the rule
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.
written in the Object class doc
Suppose I define a class named MyClass. At different times during the execution of my application I may end up writing the following code.
Object obj1 = new MyClass().getClass();
System.out.println(obj1.hashCode());
// Sometime elapses
Object obj2 = new MyClass().getClass();
System.out.println(obj2.hashCode());
System.out.println(obj1 == obj2);What I see in the print out is that the two hashcodes are sometime different while the two objects references exactly point to the same Object consistently returning true as it should be.
Any hint for this misbehaviour?Hey Hi,
This method determines which entries are offered for selection in the
dropdown list box for the salary statement. Entries can include, for
example:
o All Salary Statements
o 3 Salary Statements
o 6 Salary Statements
For each entry available for selection, you must specify the sequence
number of the oldest salary statement displayed in the hit list for
selection.
As before, you define the standard selection for this selection list.
The following export parameters are available:
Parameter - Description
EX_MESSAGE - Message
EX_VALUE_SET_EXT- ESS: Enhanced ValueSet Structure
EX_DEFAULT_ENTRY - Default entry in dropdown list
INCLUDE HRXSS_SER_VALUE_SET (ESS: Extended Value-Set Structure )
is nothing but the structurr which has following componants or you can say fields
VSKEY
VSVALUE
SEQNR
During the RUN times this fields can hold the value and export it to the portal as the Bussiness logic. -
Update set of books in implementation options ??
we are doing project setup[ in one of the test instance , How ever while doing thta in implementation options set of books is saved incorrectly and now it is freezed (not able to change the set of books field) ..Navigation setup -->system-->implementation options-->Systme Tab
can we update this set of books from back end ..and if we do where all can we get an impact ..!!
any suggestions ..Though the form field only updates the SOB in the pa_implementations_all table. It is not advised to do backend updates. I would advise to log a SR and propose your strategy which the Oracle Dev team will analyze and may approve it.
Hope this helps !
~Sathish Raju
www.projectsaccounting.com -
i have to implement the set interface without using any features, other thaset itself, from java.util. i have to create my own data structure(s) to implement it. any suggestions on which way to go.
thanks in advance.Hi,
Use java.util.Vector class as your data structure. A set is just a list that doesn't allow duplicates. You can use the Vector method: contains to figure out if it already exists or not.
import java.util.*;
public class MySet
Vector data = new Vector();
public Object get( int i )
if( i >= 0 && i < data.size() )
return( data.elementAt( i ) );
return( null );
public boolean add( Object ob )
if( !data.contains( ob ) )
data.add( ob );
return( true );
return( false );
}Regards,
Manfred. -
I have been give the task of "implementing the Set interface" in Java for a project. I believe what needs to be done is overwriting the methods I need from the Set interface, but I'm not exactly sure if this is correct, or how I would start to do this. Could anyone point me in the right direction? TIA
Edited by: prem1era on Jul 8, 2009 7:19 AM
Edited by: prem1era on Jul 8, 2009 7:25 AMOk, now that I understand more what I am doing, I have another question and maybe I should post a new topic for it, but I'll see if I can get any responses here first. Now that I am implementing Set correctly my goal is to use Set to store an object in a file instead of in memory. So this is what I have so far. For the add method, I am planning on using the object as an argument. I want to check to make sure that the object being added is not already included in that file. So within the add method I am going to read through the file, look for that object and if it is not present I am going to add it. Else, I will be returning false. Does this sound correct?
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
public class RegistrySet implements Set {
private String registryFile;
private PrintWriter pw;
public RegistrySet(String registryFile){
this.registryFile = registryFile;
public boolean add(Object o) {
return false;
} -
I have been working on implementing the Set interface, in particular my question is about the Add method. I have an internal Set within my implemented Set that keeps a copy of implemented Set. What I'm not sure about is if I am implementing it correctly. The boolean return value in the Add method is confusing me I think. Here is my code for the implemented class can you let me know if this is correct?
public RegistrySet(String registryFile){
this.registryFile = registryFile;
public void init() throws IOException {
this.br = new BufferedReader(new FileReader(this.registryFile));
this.pw = new PrintWriter(new FileWriter(this.registryFile, true));
String itemId = null;
while ( (itemId = br.readLine()) != null ){
internalSet.add(itemId);
public boolean add(Object o) {
internalSet.add(o);
Iterator it = internalSet.iterator();
while ( it.hasNext() ){
String itemId = (String)it.next();
this.pw.println(itemId);
return false;
}Edited by: prem1era on Jul 9, 2009 7:57 AMprem1era wrote:
Ok, then that is my question. How do I return what internalSet.add() returned?You're joking, right? Seriously, sit down and think for a minute. If you don't know how to do that, then you need to go back to the very beginning and not worry about trying to implement your own set right now. -
Hi, I am implementing the Set using Binary Search tree but am stuck and I cannot go further. Could someone help me get this code working? I am trying to make the add method to work but it does not compile and it says it cannot find the compareTo(java.lang.Object) method. When i don't have the compareTo method, it says i have to override the compareTo. I think i can get the contains method working if the add method works. Code below:
import java.util.*;
import java.lang.*;
public class SetImplementation<E> implements SimpleSet <E> {
private TreeNode root ;
private int NodeCount ;
public SetImplementation() {
root = null ;
NodeCount = 0 ;
public boolean add(Object obj) {
if(root == null) {
root = new TreeNode(obj) ;
NodeCount++ ;
return true ;
return recursiveAdd(root, obj) ;
public boolean recursiveAdd(TreeNode node, Object obj) {
int compareResult = (node.getObj().compareTo(obj)) ;
if(compareResult == 0) {
System.out.println("You cannot duplicate values") ;
return false;
else if(compareResult < 0) {
node.left = add( node.left, obj );
NodeCount++ ;
return true ;
else if(compareResult > 0) {
node.left = add( node.right, obj );
NodeCount++ ;
return true ;
public boolean contains(Object o) { return false ; }
public boolean isEmpty() { return root == null ; }
public int size() { return NodeCount ; }
public void clear() { root = null ; }
public class TreeNode implements Comparable {
Object obj ;
TreeNode left , right ;
public TreeNode(Object o) {
obj = o ;
left = null ;
right = null ;
public int compareTo(Object other) {
return 1; //I don't know how to do the comparison. I hav never used this interface
} //I never used the comparable interface before, so i am just out of ideas
} //So i just try to return an integer to se if it works. BUt it does not.
You're comparing the Object references from your TreeNode classes but these are not Comparable. So, you should store Comparables in your TreeNode's. And you also want to add types to your tree that are Comparable, right?
If I were you, I'd first try to get this working without the generics (the strange brackets: <E>). When that works, extend your code using generics. Here's a small start:
class SetImplementation implements SimpleSet {
public boolean add(Comparable obj) { // <-- Comparable here!
return recursiveAdd(root, obj) ;
private boolean recursiveAdd(TreeNode node, Comparable obj) { // <-- Comparable here! (and made it 'private')
int compareResult = node.obj.compareTo(obj) ;
public class TreeNode {
Comparable obj ; // <-- Comparable here!
} -
Performance issue in linux while using set with URL object
Hi,
I am facing performance issue while using Set(HashSet) with URL object on linux. But it is running perfectly on windows.
I am using
set.contains(urlObject)
Above particular statement is taking 40 sec on Linux, and only a fraction of ms on windows.
I have checked the jre version on both OS. It is the same version (jre6)
on both the OS.
Could anyone please tell me what is the exact reason, why the same statement is taking more time on linux than windows.
Thanks & Regards
Naveenjtahlborn wrote:
I believe the URL hashCode/equals implementations have some /tricky behavior which involves network access in order to run (doing hostname lookups and the like). you may want to either use simple Strings, or possibly the URI class (i think it fixed some of this behavior, although i could be wrong).The second new thing I have learned today. I was wrong in reply # 1 because looking at the URL code for 1.6 I see that the hash code is generated from the IP address and this has a lazy evaluation. Each URL placed in a HashMap (or other hash based collection) requires a DNS lookup the first time the hash code is used.
P.S. 40 seconds does seem a long time for a DNS lookup!
Edited by: sabre150 on Feb 13, 2008 3:40 PM -
Dear all,
I have an unique id made of a string. I used hashCode() to covert it to int. However, I don't like an id have the negative value.
How can I convert the hashCode() I got to an unique positive number?
Regards.
Pengyoupengyou wrote:
I see.
Now I have really a trouble in the context of Ehcache.
The net.sf.ehcache.Ehcache interface defines a method
"get(java.lang.Object key) Gets an element from the cache".
As it will use the hashcode of Object which I overwrote by string's hashcode,What? Could you rephrase that?
then I might get the wrong element for different objects.
Does it mean Ehcache is wrong the the use of it is wrong?I'm not sure I get your question, and I don't know Ehcache, so it's possible that I get you entirely wrong.
But, there's a common way to use hashCodes and it is used in caching as well, so it might be worth explaining:
As you know the hashCode() of two equal() objects (i.e. two Object a and b for which a.equals(b) and b.equals(a) return true) must always be the same.
As you learned in this thread, the opposite need not be true: two Objects for which a.equals(b) and b.equals(a) return false, might have the same hashCode(). In most (good) hashCode() implementation that occasion is relatively rare, but it can happen.
Now if you use the hashCode() to distribute a Set of objects into separate buckets, then that's fine, as long as the hashCode is not the only criterium that's used for retrieving the object.
That means that if you have found an object with the same hashCode(), then you need to check if it is indeed the correct one by calling equals(). The trick is that you only have to do that equals() call for very few objects, since most objects will have different hashCode()s. -
Window doesn't close wheh Call Library Function Node set to Run in Any Thread
This is a problem regarding Call Library Function Nodes running in the UI thread or any thread.
I have a camera which has its own API supplied as a dll. I have created a set of VI wrappers which each call a function in the dll through a Call Library Function Node.
Initially each CLFN was set to 'Run in the UI thread' (the default).
To start the camera streaming images I call (through a CLFN)
ICubeSDK_Start(int CamIndex, Hwnd, ImgHandle, bool Preview, bool callback);
If Preview = True then the image is displayed in a preview window.
If ImgHandle = NULL a default preview window
is used.
In the CLFN definition I define:
ImgHandle as a U32
Preview as a I32
To stop the camera streaming images I call
ICubeSDK_Stop(int CamIndex)
In the actual implementation I set ImgHandle = 0 (NULL) and Preview = 1 (true).
This all works fine, and a preview window is opened and images displayed. When I call ICubeSDK_Stop the preview window is closed.
However, I would prefer to set the CLFN to 'Run in any thread' because
a) when run in the UI thread the preview window randomly gets sent to the back when I switch focus between open VI windows (presumably because it is in the same thread as the VIs)
b) I don't want to put unnecessary stuff in the UI thread
c) my (naive?) understanding is that it is safer to run in any thread
So I have set all CLFNs to 'Run in any thread'
When I do this the preview window opens OK, and behaves like any other non LabVIEW controlled window in terms of focus. But when I call ICubeSDK_Stop() the preview window does not get closed properly, it just shows a blank image. I can't close it manually, there is no X in the corner and no option to close it from the taskbar. To get rid of it I have to close the LabVIEW project it is spawned from, which often results in a crash. It does appear as a separate item in task manager but if I 'end process' it, LabVIEW closes (and often crashes) as well.
If I change only the CLFNs that call the Start and Stop functions back to 'Run in the UI thread' then it all works fine again, except that the preview window gets sent to the back randomly as before.
So, what do I have to do to get the preview window to close properly if I set the CLFN to 'Run in any thread'.
Alternatively, is there a way to close the window programmatically (ie force it to close) after I have called ICube_Stop.
Thanks
DAveHi Dave,
The "Run In UI Thread" switches from the thread the VIs currently executing in to the user interface thread. If you select "Run in Any Thread", the Call Library Function Node continues in the currently executing thread. By default, all Call Library Function Nodes run in the User Interface thread.
Before you configure the Call Library Function Node to run in any thread, you have to make sure that the code is thread safe. Code is thread safe when it does not store any global data (e.g. global variables, files on disks, etc.), does not access any hardware, does not make calls to any functions, libraries or drivers that are not thread safe.
Unfortunately, since you said that your DLL accesses hardware, it is not recommended to use "Run in Any Thread." This is probably why you are seeing the crash.
If your preview window gets sent to the back you can programmatically bring it forward. Here is an example of how this can be done: http://decibel.ni.com/content/docs/DOC-4551
If you want to completely close the window down you can do so as described in this link: http://digital.ni.com/public.nsf/allkb/81E9C1441900FFCE8625748F0055DBB0?OpenDocument
I also thought you might find this useful: http://zone.ni.com/devzone/cda/tut/p/id/3009
I hope this helps.
Regards,
Mahdieh G
Applications Engineer
National Instruments UK&Ireland -
Default Setting for a Radio Group not activated when Read-Only
I have an Item on a page that is a Yes/No radio group. It is conditional read-only and has a conditional default value. Both the read-only section and the default section use PL/SQL blocks to determine there use. When the read-only condition is true the radio group is grayed out but neither the Yes or No button is checked. It then returns a null value when the page is submitted.
See
http://htmldb.oracle.com/pls/otn/f?p=24317:105
Default is Yes (http://tinypic.com/i39qh4.jpg)
Readonly is true (http://tinypic.com/i39s7p.jpg)
Rendering works fine.
But when the page is submitted, the Yes value doesnt get into session state.
This is because the read-only is implemented by setting disabled=disabled on the radio element.
As per relevant standards (http://www.htmlhelp.com/reference/html40/forms/input.html), disabled form elements are not submitted during a POST operation.
But if it is a readonly item with a default value, you already know the value (you put it there), so why do you need it in session state, just use the default value (hardcoded)
Thanks. -
JTree custom renderer setting selection background color problem
Hi,
I have a JTree with a custom icon renderer that displays an icon. The JTree is part of a TreeTable component. Iam having a problem setting the selection background uniformly for the entire row. There is no problem when there is no row selected in the JTable.
My present code looks like this:
Iam overriding paint in my renderer which extends DefaultCellRenderer.
super.paint(g);
Color bColor = null;
if(!m_selected) {
if(currRow % 2 == 0) {
bColor = Color.WHITE;
} else {
bColor = backColor;
} else {
bColor = table.getSelectionBackground(); bColor = getRowSelectionColor();
if(bColor != null) {
g.setColor(bColor);
if(!m_selected) {
g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
} else {
g.setXORMode(new Color(0x00, 0x00, 0x00));
I have a color I arrive at using some algorithm that I want using method getRowSelectionColor(). The other cells in the row have this color. But the cell containing the tree node shows different color. Iam not able to arrive at the right combination of the color to set and the xor color so my tree node also looks like the other cells in the row.
It is not a problem really as the table still looks good. Its just that the tree node looks like it has been highlighted and this might cause a problem when a table cell is highlighed later on in the application ( two cells in the row would be highlighted causing confusion).
Any help would be appreciated.
Regards,
vidyutHi Camickr,
Thanks for the reply. Iam sorry I didn't include the sources the first time around. There were too many of them. I have created a small, self-contained, compilable program that demonstrates the problem and including it herewith. Still there's quite many files but they are all needed Iam afraid. The only one you will have to concern yourself fior this problem is the file IconRenderer.java. The treenode background and the other cells background are not in sync when table row is not selected in this example though. But they are in my real program. I just need them to be in sync i.e have the same background color when the row is selected.
Your help would be very much appreciated.
These are the files that are included below:
1. AbstractTreeTableModel.java
2. Bookmarks.java
3. BookmarksModel.java
4. DynamicTreeTableModel.java
5. IconRenderer.java
6. IndicatorRenderer.java
7. JTreeTable.java
8. TreeTableExample3.java (contains main)
9. TreeTableModel.java
10. TreeTableModelAdapter.java
The copyright and javadocs information has been stripped for clarity.
cheers,
vidyut
// AbstractTreeTableModel.java BEGIN
import javax.swing.tree.*;
import javax.swing.event.*;
public abstract class AbstractTreeTableModel implements TreeTableModel {
protected Object root;
protected EventListenerList listenerList = new EventListenerList();
public AbstractTreeTableModel(Object root) {
this.root = root;
// Default implementations for methods in the TreeModel interface.
public Object getRoot() {
return root;
public boolean isLeaf(Object node) {
return getChildCount(node) == 0;
public void valueForPathChanged(TreePath path, Object newValue) {}
// This is not called in the JTree's default mode:
// use a naive implementation.
public int getIndexOfChild(Object parent, Object child) {
for (int i = 0; i < getChildCount(parent); i++) {
if (getChild(parent, i).equals(child)) {
return i;
return -1;
public void addTreeModelListener(TreeModelListener l) {
listenerList.add(TreeModelListener.class, l);
public void removeTreeModelListener(TreeModelListener l) {
listenerList.remove(TreeModelListener.class, l);
protected void fireTreeNodesChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesChanged(e);
protected void fireTreeNodesInserted(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesInserted(e);
protected void fireTreeNodesRemoved(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeNodesRemoved(e);
protected void fireTreeStructureChanged(Object source, Object[] path,
int[] childIndices,
Object[] children) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
TreeModelEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==TreeModelListener.class) {
// Lazily create the event:
if (e == null)
e = new TreeModelEvent(source, path,
childIndices, children);
((TreeModelListener)listeners[i+1]).treeStructureChanged(e);
// Default impelmentations for methods in the TreeTableModel interface.
public Class getColumnClass(int column) { return Object.class; }
public boolean isCellEditable(Object node, int column) {
return getColumnClass(column) == TreeTableModel.class;
public void setValueAt(Object aValue, Object node, int column) {}
// Left to be implemented in the subclass:
* public Object getChild(Object parent, int index)
* public int getChildCount(Object parent)
* public int getColumnCount()
* public String getColumnName(Object node, int column)
* public Object getValueAt(Object node, int column)
// AbstractTreeTableModel.java END
// Bookmarks.java BEGIN
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
public class Bookmarks {
/** The root node the bookmarks are added to. */
private BookmarkDirectory root;
* Creates a new Bookmarks object, with the entries coming from
* <code>path</code>.
public Bookmarks(String path) {
root = new BookmarkDirectory("Bookmarks");
if (path != null) {
parse(path);
* Returns the root of the bookmarks.
public BookmarkDirectory getRoot() {
return root;
protected void parse(String path) {
try {
BufferedReader reader = new BufferedReader(new FileReader
(path));
new ParserDelegator().parse(reader, new CallbackHandler(), true);
catch (IOException ioe) {
System.out.println("IOE: " + ioe);
JOptionPane.showMessageDialog(null, "Load Bookmarks",
"Unable to load bookmarks",
JOptionPane.ERROR_MESSAGE);
private static final short NO_ENTRY = 0;
private static final short BOOKMARK_ENTRY = 2;
private static final short DIRECTORY_ENTRY = 3;
private class CallbackHandler extends HTMLEditorKit.ParserCallback {
/** Parent node that new entries are added to. */
private BookmarkDirectory parent;
/** The most recently parsed tag. */
private HTML.Tag tag;
/** The last tag encountered. */
private HTML.Tag lastTag;
* The state, will be one of NO_ENTRY, DIRECTORY_ENTRY,
* or BOOKMARK_ENTRY.
private short state;
* Date for the next BookmarkDirectory node.
private Date parentDate;
* The values from the attributes are placed in here. When the
* text is encountered this is added to the node hierarchy and a
* new instance is created.
private BookmarkEntry lastBookmark;
* Creates the CallbackHandler.
public CallbackHandler() {
parent = root;
lastBookmark = new BookmarkEntry();
// HTMLEditorKit.ParserCallback methods
* Invoked when text in the html document is encountered. Based on
* the current state, this will either: do nothing
* (state == NO_ENTRY),
* create a new BookmarkEntry (state == BOOKMARK_ENTRY) or
* create a new
* BookmarkDirectory (state == DIRECTORY_ENTRY). If state is
* != NO_ENTRY, it is reset to NO_ENTRY after this is
* invoked.
public void handleText(char[] data, int pos) {
switch (state) {
case NO_ENTRY:
break;
case BOOKMARK_ENTRY:
// URL.
lastBookmark.setName(new String(data));
parent.add(lastBookmark);
lastBookmark = new BookmarkEntry();
break;
case DIRECTORY_ENTRY:
// directory.
BookmarkDirectory newParent = new
BookmarkDirectory(new String(data));
newParent.setCreated(parentDate);
parent.add(newParent);
parent = newParent;
break;
default:
break;
state = NO_ENTRY;
* Invoked when a start tag is encountered. Based on the tag
* this may update the BookmarkEntry and state, or update the
* parentDate.
public void handleStartTag(HTML.Tag t, MutableAttributeSet a,
int pos) {
lastTag = tag;
tag = t;
if (t == HTML.Tag.A && lastTag == HTML.Tag.DT) {
long lDate;
// URL
URL url;
try {
url = new URL((String)a.getAttribute(HTML.Attribute.HREF));
} catch (MalformedURLException murle) {
url = null;
lastBookmark.setLocation(url);
// created
Date date;
try {
lDate = Long.parseLong((String)a.getAttribute("add_date"));
if (lDate != 0l) {
date = new Date(1000l * lDate);
else {
date = null;
} catch (Exception ex) {
date = null;
lastBookmark.setCreated(date);
// last visited
try {
lDate = Long.parseLong((String)a.
getAttribute("last_visit"));
if (lDate != 0l) {
date = new Date(1000l * lDate);
else {
date = null;
} catch (Exception ex) {
date = null;
lastBookmark.setLastVisited(date);
state = BOOKMARK_ENTRY;
else if (t == HTML.Tag.H3 && lastTag == HTML.Tag.DT) {
// new node.
try {
parentDate = new Date(1000l * Long.parseLong((String)a.
getAttribute("add_date")));
} catch (Exception ex) {
parentDate = null;
state = DIRECTORY_ENTRY;
* Invoked when the end of a tag is encountered. If the tag is
* a DL, this will set the node that parents are added to the current
* nodes parent.
public void handleEndTag(HTML.Tag t, int pos) {
if (t == HTML.Tag.DL && parent != null) {
parent = (BookmarkDirectory)parent.getParent();
public static class BookmarkDirectory extends DefaultMutableTreeNode {
/** Dates created. */
private Date created;
public BookmarkDirectory(String name) {
super(name);
public void setName(String name) {
setUserObject(name);
public String getName() {
return (String)getUserObject();
public void setCreated(Date date) {
this.created = date;
public Date getCreated() {
return created;
public static class BookmarkEntry extends DefaultMutableTreeNode {
/** User description of the string. */
private String name;
/** The URL the bookmark represents. */
private URL location;
/** Dates the URL was last visited. */
private Date lastVisited;
/** Date the URL was created. */
private Date created;
public void setName(String name) {
this.name = name;
public String getName() {
return name;
public void setLocation(URL location) {
this.location = location;
public URL getLocation() {
return location;
public void setLastVisited(Date date) {
lastVisited = date;
public Date getLastVisited() {
return lastVisited;
public void setCreated(Date date) {
this.created = date;
public Date getCreated() {
return created;
public String toString() {
return getName();
// Bookmarks.java END
// BookmarksModel.java BEGIN
import java.util.Date;
public class BookmarksModel extends DynamicTreeTableModel {
* Names of the columns.
private static final String[] columnNames =
{ "Name", "Location", "Last Visited", "Created" };
* Method names used to access the data to display.
private static final String[] methodNames =
{ "getName", "getLocation", "getLastVisited","getCreated" };
* Method names used to set the data.
private static final String[] setterMethodNames =
{ "setName", "setLocation", "setLastVisited","setCreated" };
private static final Class[] classes =
{ TreeTableModel.class, String.class, Date.class, Date.class };
public BookmarksModel(Bookmarks.BookmarkDirectory root) {
super(root, columnNames, methodNames, setterMethodNames, classes);
public boolean isCellEditable(Object node, int column) {
switch (column) {
case 0:
// Allow editing of the name, as long as not the root.
return (node != getRoot());
case 1:
// Allow editing of the location, as long as not a
// directory
return (node instanceof Bookmarks.BookmarkEntry);
default:
// Don't allow editing of the date fields.
return false;
// BookmarksModel.java END
// DynamicTreeTableModel.java BEGIN
import java.lang.reflect.*;
import javax.swing.tree.*;
public class DynamicTreeTableModel extends AbstractTreeTableModel {
/** Names of the columns, used for the TableModel getColumnName method. */
private String[] columnNames;
private String[] methodNames;
private String[] setterMethodNames;
/** Column classes, used for the TableModel method getColumnClass. */
private Class[] cTypes;
public DynamicTreeTableModel(TreeNode root, String[] columnNames,
String[] getterMethodNames,
String[] setterMethodNames,
Class[] cTypes) {
super(root);
this.columnNames = columnNames;
this.methodNames = getterMethodNames;
this.setterMethodNames = setterMethodNames;
this.cTypes = cTypes;
public int getChildCount(Object node) {
return ((TreeNode)node).getChildCount();
public Object getChild(Object node, int i) {
return ((TreeNode)node).getChildAt(i);
public boolean isLeaf(Object node) {
return ((TreeNode)node).isLeaf();
public int getColumnCount() {
return columnNames.length;
public String getColumnName(int column) {
if (cTypes == null || column < 0 || column >= cTypes.length) {
return null;
return columnNames[column];
public Class getColumnClass(int column) {
if (cTypes == null || column < 0 || column >= cTypes.length) {
return null;
return cTypes[column];
public Object getValueAt(Object node, int column) {
try {
Method method = node.getClass().getMethod(methodNames[column],
null);
if (method != null) {
return method.invoke(node, null);
catch (Throwable th) {}
return null;
* Returns true if there is a setter method name for column
* <code>column</code>. This is set in the constructor.
public boolean isCellEditable(Object node, int column) {
return (setterMethodNames != null &&
setterMethodNames[column] != null);
// Note: This looks up the methods each time! This is rather inefficient;
// it should really be changed to cache matching
// methods/constructors
// based on <code>node</code>'s class, and code>aValue</code>'s
//class.
public void setValueAt(Object aValue, Object node, int column) {
boolean found = false;
try {
// We have to search through all the methods since the
// types may not match up.
Method[] methods = node.getClass().getMethods();
for (int counter = methods.length - 1; counter >= 0; counter--) {
if (methods[counter].getName().equals
(setterMethodNames[column]) && methods[counter].
getParameterTypes() != null && methods[counter].
getParameterTypes().length == 1) {
// We found a matching method
Class param = methods[counter].getParameterTypes()[0];
if (!param.isInstance(aValue)) {
// Yes, we can use the value passed in directly,
// no coercision is necessary!
if (aValue instanceof String &&
((String)aValue).length() == 0) {
// Assume an empty string is null, this is
// probably bogus for here.
aValue = null;
else {
// Have to attempt some sort of coercision.
// See if the expected parameter type has
// a constructor that takes a String.
Constructor cs = param.getConstructor
(new Class[] { String.class });
if (cs != null) {
aValue = cs.newInstance(new Object[]
{ aValue });
else {
aValue = null;
// null either means it was an empty string, or there
// was no translation. Could potentially deal with these
// differently.
methods[counter].invoke(node, new Object[] { aValue });
found = true;
break;
} catch (Throwable th) {
System.out.println("exception: " + th);
if (found) {
// The value changed, fire an event to notify listeners.
TreeNode parent = ((TreeNode)node).getParent();
fireTreeNodesChanged(this, getPathToRoot(parent),
new int[] { getIndexOfChild(parent, node) },
new Object[] { node });
public TreeNode[] getPathToRoot(TreeNode aNode) {
return getPathToRoot(aNode, 0);
private TreeNode[] getPathToRoot(TreeNode aNode, int depth) {
TreeNode[] retNodes;
// This method recurses, traversing towards the root in order
// size the array. On the way back, it fills in the nodes,
// starting from the root and working back to the original node.
/* Check for null, in case someone passed in a null node, or
they passed in an element that isn't rooted at root. */
if(aNode == null) {
if(depth == 0)
return null;
else
retNodes = new TreeNode[depth];
else {
depth++;
if(aNode == root)
retNodes = new TreeNode[depth];
else
retNodes = getPathToRoot(aNode.getParent(), depth);
retNodes[retNodes.length - depth] = aNode;
return retNodes;
// DynamicTreeTableModel.java END
// IconRenderer.java BEGIN
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.plaf.basic.BasicTreeUI;
class IconRenderer extends DefaultTreeCellRenderer
// Color backColor = new Color(0xD0, 0xCC, 0xFF);
Color backColor = new Color(0xF0, 0xF0, 0xE0);
String tipText = "";
JTree tree;
int currRow = 0;
boolean m_selected;
JTable table;
public IconRenderer(JTree tree, JTable table) {
this.table = table;
// setBackground(backColor);
setBackground(Color.GREEN);
setForeground(Color.black);
this.tree = tree;
public Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected,
boolean expanded, boolean leaf,
int row, boolean hasFocus) {
Object node = null;
super.getTreeCellRendererComponent(
tree, value, selected,
expanded, leaf, row,
hasFocus);
TreePath treePath = tree.getPathForRow(row);
if(treePath != null)
node = treePath.getLastPathComponent();
currRow = row;
m_selected = selected;
DefaultMutableTreeNode itc = null;
if (node instanceof DefaultMutableTreeNode) {
itc = (DefaultMutableTreeNode)node;
setClosedIcon(closedIcon);
setOpenIcon(openIcon);
return this;
/* Override the default to send back different strings for folders and leaves. */
public String getToolTipText() {
return tipText;
* Paints the value. The background is filled based on selected.
public void paint(Graphics g) {
super.paint(g);
Color bColor = null;
if(!m_selected) {
System.out.println(" iconren not sel currRow " + currRow);
if(currRow % 2 == 0) {
bColor = Color.WHITE;
} else {
bColor = backColor;
} else {
bColor = table.getSelectionBackground();
System.out.println("in else selbg = " + bColor);
bColor = new Color(0xF0, 0xCC, 0x92);
System.out.println(" bColor aft = " + bColor);
int imageOffset = -1;
if(bColor != null) {
imageOffset = getLabelStart();
g.setColor(bColor);
if(!m_selected) {
System.out.println(" not sel setting white ");
g.setXORMode(new Color(0xFF, 0xFF, 0xFF));
} else {
// g.setXORMode(new Color(0xCC, 0xCC, 0x9F));
g.setXORMode(new Color(0x00, 0x00, 0x00));
System.out.println(" using color = " + g.getColor());
if(getComponentOrientation().isLeftToRight()) {
g.fillRect(imageOffset, 0, getWidth() - 1 - imageOffset,
getHeight());
} else {
g.fillRect(0, 0, getWidth() - 1 - imageOffset,
getHeight());
private int getLabelStart() {
Icon currentI = getIcon();
if(currentI != null && getText() != null) {
return currentI.getIconWidth() + Math.max(0, getIconTextGap() - 1);
return 0;
// IconRenderer.java END
// IndicatorRenderer.java BEGIN
// import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.table.*;
import javax.swing.table.*;
import javax.swing.plaf.basic.*;
import java.awt.event.*;
import java.util.EventObject;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.StringTokenizer;
import java.util.Arrays;
class IndicatorRenderer extends DefaultTableCellRenderer {
/** Makes sure the number of displayed in an internationalized
* manner. */
protected NumberFormat formatter;
/** Row that is currently being painted. */
protected int lastRow;
protected int reloadRow;
protected int reloadCounter;
protected TreeTableModel treeTableModel;
protected TreeTableModelAdapter treeTblAdapter;
protected JTable table;
Component renderer = null;
Color backColor = new Color(0xF0, 0xF0, 0xE0);
IndicatorRenderer(TreeTableModelAdapter treeTblAdapter, TreeTableModel treeTableModel) {
setHorizontalAlignment(JLabel.RIGHT);
setFont(new Font("serif", Font.BOLD, 12));
this.treeTableModel = treeTableModel;
this.treeTblAdapter = treeTblAdapter;
* Invoked as part of DefaultTableCellRenderers implemention. Sets
* the text of the label.
public void setValue(Object value) {
/* setText((value == null) ? "---" : formatter.format(value)); */
setText((value == null) ? "---" : (String) value.toString());
* Returns this.
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
renderer = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
lastRow = row;
this.table = table;
if(isSelected) {
doMask(hasFocus, isSelected);
} else
setBackground(table.getBackground());
return renderer;
* If the row being painted is also being reloaded this will draw
* a little indicator.
public void paint(Graphics g) {
super.paint(g);
private void doMask(boolean hasFocus, boolean selected) {
maskBackground(hasFocus, selected);
private void maskBackground(boolean hasFocus, boolean selected) {
Color seed = null;
seed = table.getSelectionBackground();
Color color = seed;
if (color != null) {
setBackground(
new Color(0xF0, 0xCC, 0x92));
// IndicatorRenderer.java END
// JTreeTable.java BEGIN
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.table.*;
import java.awt.event.*;
import java.util.EventObject;
public class JTreeTable extends JTable {
/** A subclass of JTree. */
protected TreeTableCellRenderer tree;
protected IndicatorRenderer indicatorRenderer = null;
public JTreeTable(TreeTableModel treeTableModel) {
super();
// Creates the tree. It will be used as a renderer and editor.
tree = new TreeTableCellRenderer(treeTableModel);
TreeTableModelAdapter tdap = new TreeTableModelAdapter(treeTableModel, tree);
// Installs a tableModel representing the visible rows in the tree.
super.setModel(tdap);
// Forces the JTable and JTree to share their row selection models.
ListToTreeSelectionModelWrapper selectionWrapper = new
ListToTreeSelectionModelWrapper();
tree.setSelectionModel(selectionWrapper);
setSelectionModel(selectionWrapper.getListSelectionModel());
// Installs the tree editor renderer and editor.
setDefaultRenderer(TreeTableModel.class, tree);
setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
indicatorRenderer = new IndicatorRenderer(tdap, treeTableModel);
// No grid.
setShowGrid(false);
// No intercell spacing
setIntercellSpacing(new Dimension(0, 0));
// And update the height of the trees row to match that of
// the table.
//if (tree.getRowHeight() < 1) {
// Metal looks better like this.
setRowHeight(20);
public TableCellRenderer getCellRenderer(int row, int col) {
if(col == 0)
return tree;
else
return indicatorRenderer;
public void updateUI() {
super.updateUI();
if(tree != null) {
tree.updateUI();
// Do this so that the editor is referencing the current renderer
// from the tree. The renderer can potentially change each time
// laf changes.
setDefaultEditor(TreeTableModel.class, new TreeTableCellEditor());
// Use the tree's default foreground and background colors in the
// table.
LookAndFeel.installColorsAndFont(this, "Tree.background",
"Tree.foreground", "Tree.font");
public int getEditingRow() {
return (getColumnClass(editingColumn) == TreeTableModel.class) ? -1 :
editingRow;
private int realEditingRow() {
return editingRow;
public void sizeColumnsToFit(int resizingColumn) {
super.sizeColumnsToFit(resizingColumn);
if (getEditingColumn() != -1 && getColumnClass(editingColumn) ==
TreeTableModel.class) {
Rectangle cellRect = getCellRect(realEditingRow(),
getEditingColumn(), false);
Component component = getEditorComponent();
component.setBounds(cellRect);
component.validate();
public void setRowHeight(int rowHeight) {
super.setRowHeight(rowHeight);
if (tree != null && tree.getRowHeight() != rowHeight) {
tree.setRowHeight(getRowHeight());
public JTree getTree() {
return tree;
public boolean editCellAt(int row, int column, EventObject e){
boolean retValue = super.editCellAt(row, column, e);
if (retValue && getColumnClass(column) == TreeTableModel.class) {
repaint(getCellRect(row, column, false));
return retValue;
public class TreeTableCellRenderer extends JTree implements
TableCellRenderer {
/** Last table/tree row asked to renderer. */
protected int visibleRow;
/** Border to draw around the tree, if this is non-null, it will
* be painted. */
protected Border highlightBorder;
public TreeTableCellRenderer(Tr -
Hi all,
I want to know how to implement algebraic sets in PL/SQl.
I mean for example if there is a table R(A,B) where A is aprimary key having the data :-
{(1,2),(2,1),(2,3),(3,1)}
i want to have a data type that represents sets of data corresponding to attribute B.
i.e the data type should have the value {1,2,3}
Thanks.Not sure that I understand correctly.. and how you want to fit PL/SQL into this.
Sets are best handles as Oracle tables. The best language to deal with sets are SQL. So to get the results you want should be a simple:
SELECT DISTINCT b FROM table_r ORDER BY 1
The results of this can be a cursor that needs to be stepped (fetch) through.
The results can be bulk collected into a dynamic array, e.g.
create or replace type TArray is table of number;
And then in PL/SQL:declare
array TArray;
begin
SELECT DISTINCT b BULK COLLECT INTO array FROM table_r ORDER BY 1;
end;The array object will now contain TArray(1,2,3).
Maybe you are looking for
-
Alright, so like 2 hours ago i was playing with my sudoku app, and the password screen for iCloud kept popping up, so I put i my password not really thinking anything of it but it came up again, and I put the password in maybe twice more before I jus
-
HTTP response error :Connection reset
Hi all, I am getting following error in log while sending message to the trading partner and the main problem is that once this error comes then after that I am not able to send any more message to any of my Trading Partners. Even if I try to send me
-
No rfc destination is defined in SAP Global Trade Services
when doing MB1C transaction the above mentioned error is displayed(errror: No rfc destination is defined in SAP Global Trade Services ).doing MB1C transaction through movement type 561 the system is accepted,but through MT 501 when we are doing the p
-
After updates photo to get new albums that cant be deleted
in my iphone 4 i have new photo library & Camera Roll how can i move photo from photo library back to camera roll & delete the photo library?
-
MacBook Pro Retina with a 500gb hard drive - 400gb storage space?
I have a MacBook Pro Retina with a 500gb hard drive. I recently deleted a windows 8 partition, and now my macbook says its total storage capacity is 399.42gb. Is this normal? Or am I missing 100gb storage space? When I deleted the partition through b