Comparing java object trees

Hello.
I was wondering if someone might have some advice or ideas about this seemingly very common problem.
I have two copies of a very large java object tree (original and modified). I need to compare these two trees and figure out whether any data has changed. The brute force way to do this would of course be to implement equals() method for all of my objects, but in my case this would be A LOT of work.
So, I want to find a way to compare the two trees in a generic way.
My first attempt was to serialize both trees into memory and then compare them on the binary level, like this:
     public boolean autoEquals(BaseDomainObject other) {
          try {
               ByteArrayOutputStream thisObjectStream = new ByteArrayOutputStream(500);
               ObjectOutputStream out = new ObjectOutputStream(thisObjectStream);
               out.writeObject(this);
               out.flush();
               out.close();
               ByteArrayOutputStream otherObjectStream = new ByteArrayOutputStream(500);
               out = new ObjectOutputStream(otherObjectStream);
               out.writeObject(other);
               out.flush();
               out.close();
               return thisObjectStream.toString().equals(otherObjectStream.toString());
          catch (Exception e) {
               throw new RuntimeException(e);
     }This actually nearly worked, except for one problem that I do not know how to address - The order of elements in collections of the modified tree might differ from the order of the same collections in the original tree, even if the individual elements are exactly the same. My serialization idea falls apart here.
Can someone think of another way to do this?
Any ideas would be appreciated.

I thought I would follow up with the solution.
The method I described above does work, but in order to make it work I had to find a way to make all elements in all collections appear in the same order. In order to do that, I needed a unique key for each object in the tree, that would be the same in both the original and the modified tree.
In my case that was easy, b/c I get the original version from Hibernate and I make my modified version by copying it (also by serializing the original into memory and then deserializing it into my new "modified" working copy tree), so they both still contain the hibernate oids.
The extra step I needed to do before serializing and comparing was to recurse through both trees (with Introspection) and replace all sets with a TreeSet and all lists with my own implementation of a sorted list.
Now I can compare any tree of domain objects that extend from BaseDomainObject (they all do) by simply writing
domainObjectTree1.autoEquals(domainObjectTree2, new String[] {"terminatorProperty1", "terminatorProperty2", ...})
Terminator properties are basically properties which I set to null before running my comparison. This allows me to "cut off" branches of the tree that I don't want to be compared.

Similar Messages

  • Compare two Java Objects without Comparable / Comparator

    Hi Friends,
    I would like to compare two java objects (lots o attributes) without using Comparable / Comparator.
    Any suggestion/sample code would be helpful.
    Thanks,
    Sachin

    I suppose you could design another feature to compare Objects... but that would involve a design process, so asking for sample code is definitely premature. And as EJP says, what would be the point?
    At least that's what I would answer if this was one of those stupid interview questions.

  • Different ways to compare the java objects

    Hi,
    I want to compare rather search one object in collection of thousands of objects.
    And now i am using the method which uses the unique id's of objects to compare. still that is too much time consuming operation in java.
    so i want the better way to compare the objects giving me the high performance.

    If you actually tried using a HashMap, and (if necessary) if you correctly implemented certain important methods in your class (this probably wasn't necessary but might have been), and if you used HashMap in a sane way and not an insane way, then you should be getting very fast search times.
    So I conclude that one of the following is true:
    1) you really didn't try using HashMap.
    2) you tried using hashmap, but did so incorrectly (although it's actually pretty simple...)
    3) your searches are pretty fast, and any sluggishness you're seeing is caused by something else.
    4) your code isn't actually all that sluggish, but you assume it must be for some reason.
    Message was edited by:
    paulcw

  • Compare 2 encrypted String Java Objects

    Hi,
    I am have encrypted the passwords of my change password page using the java.security.messagedigest API and stored in string object.
    Can any one pls tell me how to compare these 2 encrypted objects.
    Thanks
    Hem Pushap Kaushik

    Hi,
    Message Digest can be compared using
    boolean compare = java.security.MessageDigest.isEqual(byte[] digesta, byte[] digestb) ;hope this helps.
    Regards,
    Aparajith

  • How to parse XML to Java object... please help really stuck

    Thank you for reading this email...
    If I have a **DTD** like:
    <!ELEMENT person (name, age)>
    <!ATTLIST person
         id ID #REQUIRED
    >
    <!ELEMENT name ((family, given) | (given, family))>
    <!ELEMENT age (#PCDATA)>
    <!ELEMENT family (#PCDATA)>
    <!ELEMENT given (#PCDATA)>
    the **XML** like:
    <person id="a1">
    <name>
         <family> Yoshi </family>
         <given> Samurai </given>
    </name>
    <age> 21 </age>
    </person>
    **** Could you help me to write a simple parser to parse my DTD and XML to Java object, and how can I use those objects... sorry if the problem is too basic, I am a beginner and very stuck... I am very confuse with SAXParserFactory, SAXParser, ParserAdapter and DOM has its own Factory and Parser, so confuse...
    Thank you for your help, Yo

    Hi, Yo,
    Thank you very much for your help. And I Wish you are there...I'm. And I plan to stay - It's sunny and warm here in Honolulu and the waves are up :)
    A bit more question for dear people:
    In the notes, it's mainly focus on JAXB,
    1. Is that mean JAXB is most popular parser for
    parsing XML into Java object? With me, definitely. There are essentially 3 technologies that allow you to parse XML documents:
    1) "Callbacks" (e.g. SAX in JAXP): You write a class that overrides 3 methods that will be called i) whenever the parser encounters a start tag, ii) an end tag, or iii) PCDATA. Drawback: You have to figure out where the heck in the document hierarchy you are when such a callback happens, because the same method is called on EACH start tag and similarly for the end tag and the PCDATA. You have to create the objects and put them into your own data structure - it's very tedious, but you have complete control. (Well, more or less.)
    2) "Tree" (e.g. DOM in JAXP, or it's better cousin JDOM): You call a parser that in one swoop creates an entire hierarchy that corresponds to the XML document. You don't get called on each tag as with SAX, you just get the root of the resulting tree. Drawback: All the nodes in the tree have the same type! You probably want to know which tags are in the document, don't you? Well, you'll have to traverse the tree and ask each node: What tag do you represent? And what are your attributes? (You get only strings in response even though your attributes often represent numbers.) Unless you want to display the tree - that's a nice application, you can do it as a tree model for JTree -, or otherwise don't care about the individual tags, DOM is not of much help, because you have to keep track where in the tree you are while you traverse it.
    3) Enter JAXB (or Castor, or ...): You give it a grammar of the XML documents you want to parse, or "unmarshall" as the fashion dictates to call it. (Actually the name isn't that bad, because "parsing" focuses on the input text while "unmarshalling" focuses on the objects you get, even though I'd reason that it should be marshalling that converts into objects and unmarshalling that converts objects to something else, and not vice versa but that's just my opinion.) The JAXB compiler creates a bunch of source files each with one (or now more) class(es) (and now interfaces) that correspond to the elements/tags of your grammar. (Now "compiler" is a true jevel of a misnomer, try to explain to students that after they run the "compiler", they still need to compile the sources the "compiler" generated with the real Java compiler!). Ok, you've got these sources compiled. Now you call one single method, unmarshall() and as a result you get the root node of the hierarchy that corresponds to the XML document. Sounds like DOM, but it's much better - the objects in the resulting tree don't have all the same type, but their type depends on the tag they represent. E.g if there is the tag <ball-game> then there will be an object of type myPackage.BallGame in your data structure. It gets better, if there is <score> inside <ball-game> and you have an object ballGame (of type BallGame) that you can simply call ballGame.getScore() and you get an object of type myPackage.Score. In other words, the child tags become properties of the parent object. Even better, the attributes become properties, too, so as far as your program is concerned there is no difference whether the property value was originally a tag or an attribute. On top of that, you can tell in your schema that the property has an int value - or another primitive type (that's like that in 1.0, in the early release you'll have to do it in the additional xjs file). So this is a very natural way to explore the data structure of the XML document. Of course there are drawbacks, but they are minor: daunting complexity and, as a consequence, very steep learning curve, documentation that leaves much to reader's phantasy - read trial and error - (the user's guide is too simplicistic and the examples too primitive, e.g. they don't even tell you how to make a schema where a tag has only attributes) and reference manual that has ~200 pages full of technicalities and you have to look with magnifying glas for the really usefull stuff, huge number of generated classes, some of which you may not need at all (and in 1.0 the number has doubled because each class has an accompanying interface), etc., etc. But overall, all that pales compared to the drastically improved efficiency of the programmer's efforts, i.e. your time. The time you'll spend learning the intricacies is well spent, you'll learn it once and then it will shorten your programming time all the time you use it. It's like C and Java, Java is order of magnitude more complex, but you'd probably never be sorry you gave up C.
    Of course the above essay leaves out lots and lots of detail, but I think that it touches the most important points.
    A word about JAXB 1.0 vs. Early Release (EA) version. If you have time, definitively learn 1.0, they are quite different and the main advantage is that the schema combines all the info that you had to formulate in the DTD and in the xjs file when using the EA version. I suggested EA was because you had a DTD already, but in retrospect, you better start from scratch with 1.0. The concepts in 1.0 are here to stay and once your surmounted the learning curve, you'll be glad that you don't have to switch concepts.
    When parser job is done,
    what kind of Java Object we will get? (String,
    InputStream or ...)See above, typically it's an object whose type is defined as a class (and interface in 1.0) within the sources that JABX generates. Or it can be a String or one of the primitive types - you tell the "compiler" in the schema (xjs file in EA) what you want!
    2. If we want to use JAXB, we have to contain a
    XJS-file? Something like:In EA, yes. In 1.0 no - it's all in the schema.
    I am very new to XML, is there any simpler way to get
    around them? It has already take me 4 days to find a
    simple parser which give it XML and DTD, then return
    to me Java objects ... I mean if that kind of parser
    exists....It'll take you probably magnitude longer that that to get really familiar with JAXB, but believe me it's worth it. You'll save countless days if not weeks once you'll start developing serious software with it. How long did it take you to learn Java and it's main APIs? You'll either invest the time learning how to use the software others have written, or you invest it writing it yourself. I'll take the former any time. But it's only my opinion...
    Jan

  • Parse of a xml file to an java object model

    Hello,
    I'm trying to do a program that receive an xml file and ought to create all the neccesary java objects according to the content of the parsed xml file.
    I've all the class created for all the objects that could be present into the xml and the idea is to go down in the tree of nodes recursively until it returns nodes more simple. Then, I create the last object and while I come back of the recursively calls, I create the objects more complex until I reached to the main object.
    Until now, I have part of this code, that is the one wich have to parse the parts of the xml.
    public static void readFile(String root){
              DocumentBuilderFactory factory = DocumentBuilderFactory
                   .newInstance();
              try {
                   DocumentBuilder builder = factory.newDocumentBuilder();
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   String contents = scanner.next();
                   scanner.close();
                   Document document = builder.parse(new ByteArrayInputStream(contents.getBytes()));
                   Node node = null;
                   NodeList nodes = null;
                   Element element = document.getDocumentElement();
                   System.out.println(element.getNodeName());
                   NodeList subNodes;
                   NamedNodeMap attributes;
                   //if (element.hasAttributes())
                   visitNodes(element);
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
              } catch (SAXException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                   e.printStackTrace();
         private static void visitNodes (Node node){
              for(Node childNode = node.getFirstChild(); childNode!=null;){
                   if (childNode.getNodeType() == childNode.DOCUMENT_NODE){
                        System.out.println("Document node Name " + childNode.getNodeName());
                        visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.ELEMENT_NODE){
                        System.out.println("Node Name " + childNode.getNodeName());
                        if (childNode.hasAttributes()){
                             visitAttributes(childNode.getAttributes());
                        if (childNode.hasChildNodes()){
                             visitNodes(childNode);
                   }else if (childNode.getNodeType() == childNode.TEXT_NODE && !childNode.getNodeValue().contains("\n\t")){
                        System.out.println("Node value " + childNode.getNodeValue());
                   Node nextChild = childNode.getNextSibling();
                   childNode = nextChild;
         private static void visitAttributes(NamedNodeMap attributes){
              Node node;
              for(int i = 0; i < attributes.getLength(); i++){
                   node = attributes.item(i);
                   System.out.print(node.getNodeName() + " ");
                   System.out.print(node.getNodeValue() + " ");
                  }I don't know the use of childNodeType. For example, I expected that the XML tags with childs in his structure, enter by the option NODE_DOCUMENT and the tags without childs by the ELEMENT_NODE.
    But the most important problem I've found are the nodes [#text] because after one ELEMENT_NODE I always found this node and when I ask if the node hasChilds, always returns true by this node.
    Has any option to obtain this text value, that finally I want to display without doing other recursively call when I enter into the ELEMENT_NODE option?
    When one Node is of type DOCUMENT_NODE or DOCUMENT_COMMENT? My program always enter by the ELEMENT_NODE type
    Have you any other suggestions? All the help or idea will be well received.
    Thanks for all.

    Hello again,
    My native language is Spanish and sorry by my English I attemp write as better I can, using my own knowledge and the google traductor.
    I have solved my initial problem with the xml parser.
    Firstly, I read the complete XML file, validated previously.
    The code I've used is this:
    public static String readCompleteFile (String root){
              String content = "";
              try {
                   Scanner scanner = new Scanner(new File(root)).useDelimiter("\\Z");
                   content = scanner.next();
                   scanner.close();
              } catch (IOException e) {
                   e.printStackTrace();
              return content;
         }Now, I've the file in memory and I hope I can explain me better.
    I can receive different types of XML that could be or not partly equals.
    For this purpose I've created an external jar library with all the possible objects contained in my xml files.
    Each one of this objects depend on other, until found leaf nodes.
    For example, If I receive one xml with a scheme like the next:
    <Person>
        <Name>Juliet</Name>
        <Father Age="30r">Peter</Father>
        <Mother age="29">Theresa</Mother>
        <Brother>
        </Brother>
        <Education>
            <School>
            </school>
        </education>
    </person>
    <person>
    </person>The first class, which initializes the parse, should selecting all the person tags into the file and treat them one by one. This means that for each person tag found, I must to call each subobject wich appears in the tag. using as parameter his own part of the tag and so on until you reach a node that has no more than values and or attributes. When the last node is completed I'm going to go back for completing the parent objects until I return to the original object. Then I'll have all the XML in java objects.
    The method that I must implement as constructor in every object is similar to this:
    public class Person{
      final String[] SUBOBJETOS = {"Father", "Mother", "Brothers", "Education"};
      private String name;
         private Father father;
         private Mother mother;
         private ArrayList brothers;
         private Education education;
         public Person(String xml){
           XmlUtil utilXml = new XmlUtil();          
              String xmlFather = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[0]);
              String xmlMother = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[1]);
              String xmlBrothers = utilXml.textBetweenMultipleXmlTags(xml, SUBOBJETOS[2]);
              String xmlEducation = utilXml.textBetweenXmlTags(xml, SUBOBJETOS[3]);
              if (!xmlFather.equals("")){
                   this.setFather(new Father(xmlFather));
              if (!xmlMother.equals("")){
                   this.setMother(new Father(xmlMother));
              if (!xmlBrothers.equals("")){
                ArrayList aux = new ArrayList();
                String xmlBrother;
                while xmlBrothers != null && !xmlBrothers.equals("")){
                  xmlBrother = utilXml.textBetweenXmlTags(xmlBrothers, SUBOBJETOS[2]);
                  aux.add(new Brother(xmlBrother);
                  xmlBrothers = utilXml.removeTagTreated(xmlBrothers, SUBOBJETOS[2]);
                this.setBrothers(aux);
              if (!xmlEducation.equals("")){
                   this.setEducation(new Father(xmlEducation));     
    }If the object is a leaf object, the constructor will be like this:
    public class Mother {
         //Elements
         private String name;
         private String age;
         public Mother(String xml){          
              XmlUtil utilXml = new XmlUtil();
              HashMap objects = utilXml.parsearString(xml);
              ArraysList objectsList = new ArrayList();
              String[] Object = new String[2];
              this.setName((String)objects.get("Mother"));
              if (objects.get("attributes")!= null){
                   objectsList = objects.get("attributes");
                   for (int i = 0; i < objectsList.size();i++){
                     Object = objectsList.get(i);
                     if (object[0].equals("age"))
                       this.setAge(object[1]);
                     else
         }Each class will have its getter and setter but I do not have implemented in the examples.
    Finally, the parser is as follows:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import javax.xml.parsers.DocumentBuilder;
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.ParserConfigurationException;
    import org.w3c.dom.Document;
    import org.w3c.dom.NamedNodeMap;
    import org.w3c.dom.Node;
    import org.xml.sax.SAXException;
    public class XmlUtil {
         public HashMap parsearString(String contenido){
              HashMap objet = new HashMap();
              DocumentBuilderFactory factory;
              DocumentBuilder builder;
              Document document;
              try{
                   if (content != null && !content.equals("")){
                        factory = DocumentBuilderFactory.newInstance();
                        builder = factory.newDocumentBuilder();
                        document = builder.parse(new ByteArrayInputStream(content.getBytes()));
                        object = visitNodes(document);                    
                   }else{
                        object = null;
              } catch (ParserConfigurationException e) {
                   e.printStackTrace();
                   return null;
              } catch (SAXException e) {
                   e.printStackTrace();
                   return null;
              } catch (IOException e) {
                   e.printStackTrace();
                   return null;
              return object;
         private HashMap visitNodes (Node node){
              String nodeName = "";
              String nodeValue = "";
              ArrayList attributes = new ArrayList();
              HashMap object = new HashMap();
              Node childNode = node.getFirstChild();
              if (childNode.getNodeType() == Node.ELEMENT_NODE){
                   nodeName = childNode.getNodeName();                    
                   if (childNode.hasAttributes()){
                        attributes = visitAttributes(childNode.getAttributes());
                   }else{
                        attributes = null;
                   nodeValue = getNodeValue(childNode);
                   object.put(nodeName, nodeValue);
                   object.put("attributes", attributes);
              return object;
         private static String getNodeValue (Node node){          
              if (node.hasChildNodes() && node.getFirstChild().getNodeType() == Node.TEXT_NODE && !node.getFirstChild().getNodeValue().contains("\n\t"))
                   return node.getFirstChild().getNodeValue();
              else
                   return "";
         private ArrayList visitAttributes(NamedNodeMap attributes){
              Node node;
              ArrayList ListAttributes = new ArrayList();
              String [] attribute = new String[2];
              for(int i = 0; i < attributes.getLength(); i++){
                   atribute = new String[2];
                   node = attributes.item(i);
                   if (node.getNodeType() == Node.ATTRIBUTE_NODE){
                        attribute[0] = node.getNodeName();
                        attribute[1] = node.getNodeValue();
                        ListAttributes.add(attribute);
              return ListAttributes;
    }This code functioning properly. However, as exist around 400 objects to the xml, I wanted to create a method for more easily invoking objects that are below other and that's what I can't get to do at the moment.
    The code I use is:
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class UtilClasses {
         public Object UtilClasses(String package, String object, String xml){
              try {
                Class class = Class.forName(package + "." + object);
                //parameter types for methods
                Class[] partypes = new Class[]{Object.class};
                //Create method object . methodname and parameter types
                Method meth = class.getMethod(object, partypes);
                //parameter types for constructor
                Class[] constrpartypes = new Class[]{String.class};
                //Create constructor object . parameter types
                Constructor constr = claseObjeto.getConstructor(constrpartypes);
                //create instance
                Object obj = constr.newInstance(new String[]{xml});
                //Arguments to be passed into method
                Object[] arglist = new Object[]{xml};
                //invoke method!!
                String output = (String) meth.invoke(dummyto, arglist);
                System.out.println(output);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
              return null;
         }This is an example obtained from the Internet that I've wanted modified to my needs. The problem is that when the class calls this method to invoke the constructor and does not fail, this does not do what I expect, because it creates an empty constructor. If not, the parent class gives a casting error.
    I hope that now have been more clear my intentions and that no one has fallen asleep reading this lengthy explanation.
    greetings.

  • Create java objects from xml

    I want to create a tree structure for java object. These java objects are populated after the parsing the xml. But what could be the logic for adding child to parent when there are
    many sub nodes? I wanted to use one recursive function which iterate through all the elements of the xml file. But I have not got the idea how to add one child object to parent object.
    following are my classes. Any help on this highly appreciated.
    public class TreeObject {
              private String name;
              private TreeParent parent;
              public TreeObject(String name) {
                   this.name = name;
              public String getName() {
                   return name;
              public void setParent(TreeParent parent) {
                   this.parent = parent;
              public TreeParent getParent() {
                   return parent;
              public String toString() {
                   return getName();
    import java.util.ArrayList;
    public class TreeParent extends TreeObject {
         private TreeObject treeObject ;
              private ArrayList children;
              public TreeParent(String name) {
                   super(name);
                   children = new ArrayList();
              public void addChild(TreeObject child) {
                   children.add(child);
                   child.setParent(this);
                   treeObject = child ;
              public void removeChild(TreeObject child) {
                   children.remove(child);
                   child.setParent(null);
              public TreeObject [] getChildren() {
                   return (TreeObject [])children.toArray(new TreeObject[children.size()]);
              public boolean hasChildren() {
                   return children.size()>0;
              public TreeObject getChild(){
                   return treeObject;
    private TreeParent getChilderen(Element rootNode){
         List list = rootNode.getChildren();
         String rootNodeName = rootNode.getName();
         TreeParent root = new TreeParent(rootNodeName);
         for (int i=0; i< list.size(); i++)
    Element node = (Element) list.get(i);
    if(node.getChildren().size() > 0){
         // TreeParent treeParent = new TreeParent(node.getText());
         TreeParent treesub = new TreeParent(node.getText());
         treesub.addChild(treesub);
         //TreeParent p = treeParent.getParent();
         // rootParent.addChild(treeParent);
    }else{
         TreeObject object = new TreeObject(node.getText());
         root.addChild(object);
    getChilderen(node);
         return root ;
    public TreeParent buildTree(String filePath) {
    SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File(filePath);
    try{
    Document document = (Document) builder.build(xmlFile);
    Element rootNode = document.getRootElement();
    // List list = rootNode.getChildren("staff");
    TreeParent rootParent = getChilderen(rootNode);
    return rootParent ;
    }catch(IOException io){
    System.out.println(io.getMessage());
    }catch(JDOMException jdomex){
    System.out.println(jdomex.getMessage());
    return null;
    Edited by: 870611 on Jul 6, 2011 6:27 AM

    Hi
    I recommend you use the API JAXB. Is much simpler.
    here a link: http://www.oracle.com/technetwork/articles/javase/index-140168.html
    here a example: http://download.oracle.com/javaee/5/tutorial/doc/bnbay.html#bnbbc

  • Oracle Application Server 10g Java Object Cache

    Hi,
    I am new to Java and looking for a java caching framework and just came across Oracle Application Server 10g Java Object Cache. I am unable to find 11g version of the same. Is it not supported any more?
    Can I use this with weblogic server? Please suggest if any other alternatives.
    Thanks,
    Manoj

    Bump.
    I definitely don't see the same file: C:\dev\jdevstudio10134\javacache\lib\cache.jar in the Oracle JDEV tree. Is there a suggested alternative?

  • Traverse object tree from the middle with reflection

    Hi.
    I am new to using reflection in more complex scenarios, and would like some advice.
    If I get back a partial object tree, from an ORM layer for example, where I have a series of associated objects, for example Employee, which has a Department attribute, linking it to its parent department, and a collection of child address objects, is it possible to traverse all objects attached to Employee, calling a given method on them, if they extend a certain class?
    Could someone show an example of doing this, or describe how it could be done?
    Thanks for your help.

    You have an arbritrarily complex hierarchial collection whith a unknown structure.
    You wish to apply a method to all references in the tree.
    There are only two basic storage mechanisms in java; reference or array.
    Setup: Keep a hashtable/dictionary of each visited reference to avoid endless recursion.
    Method, called Doit() which takes an Object 'n'
    - If n is null return
    - if n is already in hashtable return
    - Add to hashtable
    - if n is of type base class then call target method (might want to decide about thrown exception.)
    - reflect through n for members which are either Object or array (base type Object)
    - If single member is Object then call Doit
    - If array recurse through each item and call Doit()

  • Assistance in comparing 2 Objects

    I have got a problem... I am currently trying to compare 2 Objects together and checking upon their IDs and after that is done, it will then update the quantity of it... Below is my coding and hopefully, it will share some light on what I am trying to achieve...
    [Bindable]
    private var shopCartXML:XML = new XML(<product></product>);
    [Bindable]
    private var shopCartData:XMLListCollection;
    private function addCart():void
                    var itemUpdate:XMLList = shopCartXML.product.(@category==musicTree.selectedItem.@category);
                    //var itemUpdate2:XMLList = shopCartXML.product.@id == musicTree.selectedItem.@id);
                    var testUpdate:Object = musicTree.selectedItem.@id;
                   for  each (var item:Object in shopCartXML)
                       // 0 returns true, 1 and -1 for differences
                       var testItem:int = ObjectUtil.compare(item.product.@id, testUpdate, 0);
                        trace (testItem);
                        if ((testItem)  && (itemUpdate.length() > 0))
                            itemUpdate.sing_quantity = Number(itemUpdate.sing_quantity) + 1;
                        else
                            var newData:XML =
                                                    <product id={musicTree.selectedItem.@id} category={musicTree.selectedItem.@category}>
                                                        <name>
                                                            {musicTree.selectedItem.@name}
                                                        </name>
                                                        <category>
                                                            {musicTree.selectedItem.@category}
                                                        </category>
                                                        <sing_price>
                                                            {musicTree.selectedItem.@sing_price}
                                                        </sing_price>
                                                        <sing_quantity>
                                                            {musicTree.selectedItem.@sing_quantity}
                                                        </sing_quantity>
                                                    </product>;
                             shopCartXML.appendChild(newData);
                            // We create the XMLListCollection as this will bring alot of functionalities like binding of data or update upon new changes
                            shopCartData =  new XMLListCollection(shopCartXML.children());           
    Basically, I am trying to do is that after the the click of the button, it will come to this addCart function and within this function, it would firstly create a shopCartXML of XML and update the details into the shopCartData and it would be displayed into the data grid. But the real problem with this is that, I would want to validate on the product's id and its category. Because, at the moment, it will only validate on the category but not on the ID. Thus, when I have got 2 items of the same category but different IDs, it will only increase on the quantity of the 1st item, which I have added but it will not add the 2nd item to the data grid and it will only increase on the quantity of the 1st item....
    I been working on this for 2 nights and still I have not managed to come up with a solution to solve this problem... Any ideas on where I am going wrong?? I tried my hands on ObjectUtil.compare and for each in loop but still I am not able to compare the shopCartXML ID and the Tree control selectedItem ID...

    Hi there, what is your issue?
    Sincerely,
    Michael
    El 10/05/2009, a las 21:20, addytoe85 <[email protected]> escribió:
    >
    I have got a problem... I am currently trying to compare 2 Objects 
    together and checking upon their IDs and after that is done, it will 
    then update the quantity of it... Below is my coding and hopefully, 
    it will share some light on what I am trying to achieve...
    >
    private var shopCartXML:XML = new XML(<product></product>);
    >
    private var shopCartData:XMLListCollection;
    >
    private function addCart():void
    >
                    var itemUpdate:XMLList = shopCartXML.product.
    (@category==musicTree.selectedItem.@category);
                    //var itemUpdate2:XMLList = shopCartXML.product.@id 
    == musicTree.selectedItem.@id);
                    var testUpdate:Object = musicTree.selectedItem.@id;
    >
                    for  each (var item:Object in shopCartXML)
    >
                        // 0 returns true, 1 and -1 for differences
                        var testItem:int = 
    ObjectUtil.compare(item.product.@id, testUpdate, 0);
                        trace (testItem);
    >
                        if ((testItem)  && (itemUpdate.length() > 0))
                            itemUpdate.sing_quantity = 
    Number(itemUpdate.sing_quantity) + 1;
                        else
    >
    var newData:XML =
                                                    <product 
    id={musicTree.selectedItem.@id} 
    category={musicTree.selectedItem.@category}>
    >
                                                        <name>
    {musicTree.selectedItem.@name}
                                                        </name>
    >
                                                        <category>
    {musicTree.selectedItem.@category}
                                                        </category>
    >
                                                        <sing_price>
    {musicTree.selectedItem.@sing_price}
                                                        </sing_price>
    >

  • Using expression to compare Calendar object

    Hi,
    I wonder if anyone has experience to use expression to compare Calendar object. Here is my case:
    Application {
    Calendar applicationDate;
    What I want is something like:
    expression.get("applicationDate").between(startDate, endDate);
    But it is seems not working this way.
    Any clue?
    Thanks
    Hao

    What error are you getting, in general this should work, however the Calendar will be printed/bound as a java.sql.Timestamp.
    If you require to use java.sql.Date if you just want the date portion of the Calendar.
    If your mapping for applicationDate sets the fieldClassification (i.e. is a TypeConversionMapping), then TopLink will automatically convert the Calendar value in the expression to the correct date type.

  • Compare 2 objects - urgent

    hi all
    i have a problem.
    I want to compare two objects but dono how.
    Object obj1=null, obj2=null;
    Vector vec = new Vector()
    obj1=vec
    Vector vec1=new Vector()
    obj2=vec
    now i want to compare if(obj1 == obj2)
    how can i do this
    help out plzzzzzzzzzzzzzzzzz
    thanx

    Nope, I'm still scratching my head over this one.
    However, there are two comparisions in java.
    ==, and .equals() method
    == just checks to see if the Object is the same Object
    .equals() is defined to check if one Object is equal to another.
    quick example:
      String s1 = new String("Hello");
      String s2 = s1;
      String s3 = new String("Hello");
      String s4 = new String("GoodBye");
      s1 == s2;  // true because they are the same object
      s1.equals(s2) // true because they have the same underlying value
      s1 == s3  // false because they are different objects
      s1.equals(s3) // true, because the are the same underlying value
      s1 == s3 // false
      s1.equals(s4)// also falseAny time you want to compare the VALUE of two objects, use the .equals method.
    So in this case,
    if (oldObj.equals(newObj)) is the way to go
    If you are dealing with vectors/lists, the equals method will compare every item in oldObj with every item in newObj. If they are all equal, then it will return true.
    Hope this helps,
    evnafets

  • Comparing two Objects

    Hi, I want to compare two objects
    using the formula below
    if((Integer)v.elementAt(i) == new Integer(comp.getCard(j).getValue())){but it doesn't work
    I am trying to compare an element in a vector which was of a type Integer
    key1 = new Integer(dk.getCard(f).getValue());note that key1 is actually a key used for a mapping
    can anyone tell me how I can compare the elements in vector and the other object was an int.

A: Comparing two Objects

Hello zainuluk,
You can not use '==' operator to compare to objects in Java, 'cause it just compare the reference of two oprands. You should use the "equals()" method, just like this:
if(Integer)v.elementAt(i).equals(new Integer(comp.getCard(j).getValue())){...}
Or you can get the int value of element in the vector to compare using '==' operator:
if(Integer)v.elementAt(i).intValue() == comp.getCard(j).getValue()){..}

Hello zainuluk,
You can not use '==' operator to compare to objects in Java, 'cause it just compare the reference of two oprands. You should use the "equals()" method, just like this:
if(Integer)v.elementAt(i).equals(new Integer(comp.getCard(j).getValue())){...}
Or you can get the int value of element in the vector to compare using '==' operator:
if(Integer)v.elementAt(i).intValue() == comp.getCard(j).getValue()){..}

  • The Proper way to go - Passing Serialized Java Objects vs. Web Services?

    The team which I am apart of in our little "community" is trying to convince some "others" (management) that we should not use web services to communicate (move large data) within the same application (allbeit a huge application spanning across many servers).
    Furthermore these "others" are trying to tell us that in this same application when two small apps. inside of this large app. are both java we should not communicate via serialized java objects but instead we should use Web Services and XML. We are trying to convince them that the simplest way is best.
    They have asked us to provide them with proof that passing serialized java objects back and forth between two smaller java applications inside of a larger one is an Industry Standard. Can anyone help either straighten my fellow workers and I out or help us convince the "others" of the proper way to go?

    When I was a consultant we always gave the client what they wanted. Even if it was the wrong choice. Suck it up.
    I'm glad I wasn't one of those customers. Although I agree that a customer is the one who decides what to do, when I pay someone for consultancy, I expect them to consult me. If they know I'm trying to do something that I shouldn't be doing, I expect a good consultant to be able to show me that there's a better way (not just tell me I'm not doing it right, mind you).
    We pass a lot of data using XML and we don't have any transmission or processing speed issues.
    Then you either have a much better network than our customer did, or we're not talking about the same amounts of data here.
    I used the JAX-RPC RI ...
    That's cool... our customer was, unfortunately, infected with Borland products, so we had to use BES. The web services on BES were run by Axis.
    How large were these messages?
    Huge... each element had about 15 attributes, so 1,200 elements would require 19,200 XML nodes (envelope not included). By comparison, the serialized messages weren't even a quarter that size. It's not just about what you send across the network; it's also the effort of parsing XML compared to desrializing Java objects. Our web service wasn't exactly the only process running at the server.
    Anyone who understand the fundamental difference between ASCII (XML) and binary (serialized) formats realizes that no web service can possibly achieve the performance of binary Java services. Why do you think that work is being put into binary web services? I'm not saying XML is never a good thing; just that it's not The Holy Grail that a lot of people are making it look like.
    http://issues.apache.org/jira/browse/AXIS-688
    Ouch.

  • Compare XI objects

    I have two questions.
    1. Which Tcode can be used to compare two XI objects crossclient just as SE39 does this job for abap.
    2. Given a scenario.Ex in DEV i have mapping object X .In PRD same object has already been moved befor e, but not by CTS+
    or CMS  (i mean only file transport).
    Now i try to use CMS or CTS+ today.Will transport management system not deny me saying that previous versions are not identical?(Looking for an expert opinion here).

    >>Mr Jaishankar ,there are so many UDF's ,Huge mapping (graphical),Fixed values.How can one guess a change ?.
    You can't. That is why I said it is manual and not automatic.
    >>I remember a gentleman from this forum itself applauding about XI transport system and consulting me to go through version and change management.I am actually impressed gentleman.
    May be the gentleman knows more than me.
    >>I attribute this to poor design of XI ,whether its repository managment,change management and transport management.
    You are comparing an ABAP object with a Java object (and not just a java code but a graphical representation of a Java code) here. Remember there is a lot of difference. But I agree, it could have been better and let us wait for other experts opinion before saying this is all bad.
    Regards
    Jai

  • Maybe you are looking for