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.

Similar Messages

  • Compare two similar objects

    Do you know about any possible Java bugs with JDK update?
    In my case, my code stopped working.
    Here is what I have. There are two similar objects, but Object 1 has key, and Object 2 (same as Object 1) has no key. I need to compare both, and if they are equal, I need Object 1 to assign key to Object 2.
    It worked before. How I can get around.
    Please help me if you can.
    Respectfully,
    Alex

    Let me change the question:
    "Can we compare two objects one with key and another one without key? How?

  • Comparing Two Jtree Objects

    Hi
    I had constructed two JTree objects. Now i want to find the difference between these two JTree's Node wise.I dont have any idea how to proceed further.If some one help me in this regard i would be very thankful.
    -Rosy

    The JTree component handles the 'view' side of things. The actual data it displays is held in a TreeModel. You can create your own and pass it to the JTree when you create it otherwise a DefaultTreeModel is created for you by the JTree.
    What I'm getting at is that to achieve your aim you want to compare the TreeModels rather than the JTrees.
    If you haven't created your own, you can get it from the JTree using jTree.getModel()
    Calling methods on each model and comparing the results will achieve your aim.

  • How to compare two database objects?

    Hi,
    I need to compare two objects with embedded objects/collections in it to tell exact difference between the two.
    e.g.,
    create type t1 as object (name varchar2(10), age number);
    create type t2 as table of t1;
    create type t3 as object (user t1, family t2);
    ... and so on.. this type hirarechy is big in my case..
    I want a procedure/function which can tell me what and where is the difference.
    PROCEDURE (obj1 T1 , obj2 T1) IS
    BEGIN
    END;
    e.g., t1.name = 'John' and t2.name = 'Mich' then it should return t1.name etc..
    Is it possible?
    Thanks

    Why a new thread?
    how to read objects/collections dynamically?

  • How to RELIABLY compare two File objects?

    Hi java community!
    I have two File objects and I need to know whether they both point to the same file on the system. First, I tried using the equals() method of the File object, but later I found that this often returns false even when file being pointed to by both objects is the same file.
    For example:
      public static void main(String[] args) throws Exception {
        File mFileA = new File("C:\\PROGRA~1\\MYPROG~1\\MYDATA~1.TXT");
        File mFileB = new File("C:\\Program Files\\My Program\\My Data File.txt");
        DataInputStream mInputA = new DataInputStream(new BufferedInputStream(new FileInputStream(mFileA)));
        DataInputStream mInputB = new DataInputStream(new BufferedInputStream(new FileInputStream(mFileB)));
        System.out.println("Contents of file A:");
        while (mInputA.available() > 0) {
          System.out.println(mInputA.readLine());
        System.out.println("\nContents of file B:");
        while (mInputB.available() > 0) {
          System.out.println(mInputB.readLine());
        System.out.println("\nAre file A and file B the same file?");
        System.out.println(mFileA.equals(mFileB) ? "Yes" : "No");
      }Running this gives the following output:
    Contents of file A:
    First line of the file.
    Second line of the file.
    Third and final line of the file.
    Contents of file B:
    First line of the file.
    Second line of the file.
    Third and final line of the file.
    Are file A and file B the same file?
    NoIt seems that the different representation of the paths (short 8.3 file names, vs. long file names) is confusing Java into believing that they are two separate files, even though the example above confirms that they are in fact the same file by showing the contents from input streams derived by the two File objects (which are, needless to say, identical).
    So, does anyone know how to reliably determine whether two File objects point to the same file?
    Cheers,
    Martin

    sabre150 wrote:
    Bren_McGuire wrote:
    Thanks guys.
    I'd just found it too right after I made this post. :p95% of the time the promised Dukes never arrive so thanks for the Dukes.Ditto

  • How to compare two date Objects

    Hi,
    I have two Calendar Objects, one is coming from client and one is my server time, I need to evaluate that incoming time with server time so that if it is sent before an hour back then i should not do anything on that request Object. I have converted the incoming String into Calendar Object and how can i evaluate these two Calendar Objects including their hours and minutes.
    Thanks in advance
    bajju

    bajjurireddy, ignore Mobiquity's post. It contains no useful information and will only serve to confuse and frustrate you.
    Mobiquity wrote:
    Also make sure that the two date objects are in the same date format..
    public static String DateToDateString(java.util.Date d, String dateFormat)
         throws ParseException {
              SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
              sdf.setLenient(false); // this is required else it will convert
              String dateString = sdf.format(d);
              return dateString;

  • Saving java objects without serialization

    Hi!
    I want to save a lot of java objects to file, and be able to restore the data structure that these java objects compose.
    The obvious way to do that, is to use some kind of serialization I guess. But, as I see it, the problem with this approach is that as the data structure expands and new classes are added and present classes are changed (even the name of the classes) this approach fails. If the user has an old data structure that he/she wants to restore there will be a problem with e.g. ClassCastException and the like.
    Now I am wondering if someone could give me some hints of how to solve this problem. What approach should I use instead. Is XML the right way to do it? Someone who has any experience with these problems?
    I would really appreciate some help!
    Best regards
    Lars

    Hi, Lars, funny you should mention this issue. I am
    dealing with the exact same problem at work. Every
    time I release a new version of my software, users
    cannot load files they saved with the previous
    version. This is a big problem !
    And, like you, I am toying with the XML solution.
    On the downside, saving these objects in an XML format
    will take more memory, as XML can be (and should be?)
    textually descriptive. Those ASCII tags and such will
    probably treble the file size of their streamlined
    "serialized" predecessors.
    But memory is cheap, eh ?
    On the plus side, your XML parser can be (by it's nature)
    forgiving if new fields have been added or old ones taken
    away. And that is why Serializable is giving be a headache
    to begin with !
    Two other thoughts cross my mind ...
    For exceedingly large files, a SAX parser (vice DOM) will
    only have a bit 'o the structure in memory at a time, instead
    of having the whole kit and kaboodle in memory (my understanding
    of DOM).
    Also, nothing is stopping me from taking a gander at some of
    the Zip packages ... now where did I run across them ? java.io ? ...
    where once I write out the XML file (saving my objects), I could
    compress 'em for the user, too :-) I seem to recall a ZipStream or
    something while scanning some of the (JDK 1.4?) packages.
    I am looking forward to your response, and those of other interested
    readers sharing their thoughts on this topic, too !
    Eric

  • Images XOR, AND, etc... logical operators to compare two distinct objects

    is there a way of comper two images without comparing all it bytes...
    the problem: actually I�m parsing the values of the bytes of the two images and then comparing it...
    idea: if I have the two byte arrays containing the image info.. may I use a logical operator to compare these objects ??

    FelipeGaucho again,
    Did you come up with an optimized method for logical operators? I actually want to perform the boolean operations to turn most pixels of an image to zero, then compress that (as in your post 'String compressor II'). Are these two posts related for you as well? They are separated by several months.
    abnormal,
    I'm assuming that Java's classes would be optimized, but if my code will execute at the same speed as theirs, then I guess I can stop searching for optimized (or already provided) classes. Do you know if Java's provided classes run faster than classes we create? I'm going to test the provided System.arraycopy against my own while waiting for a reply.

  • 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

  • How to bind dynamic xml with Java objects without xsd

    have a question, and hope someone here can help me.
    In my current project, I will get a xml file, containing some information of each user, and map them into a set of user objects.
    For each user, there are some fixed attributes, such as name, phone#, age, position, etc. The problem is, client can customize, and add new attibutes, such as address, favorite color, so there will be no xsd for the xml.
    What I want to do, is map fixed attributes to user object attributes, for example, name attribute to User.name, and they will have corresponding getters, and setters, but for custom attributes, I want to add them to a HashMap in User object, for example, use string "ADDRESS" as the key, and address as the value.
    Is there any way I can do this? Thank you very much for any help you can provide.

    It would not be too hard to do in regular code.
    First, make a HashSet with the Strings for the names of the known attributes that will be processed with setters.
    Then, get the NamedNodeMap via getAttributes(). That will give you all attributes -- both the ones you will handle with your setters and the ones you will handle via a HashMap.
    Then, loop through the NamedNodeMap. For each attribute, get the name and value. If the name is in the HashSet of known values, process it with a list of
    if ( attName.equals( "name" ))
        whatever.setName( value );
       continue;
    }If it is not in the HashSet, then set the value into your HashMap with the name and value.
    There is no standard way to do this.
    Dave Patterson

  • Functinality to compare two material price with reference to BOM in CO

    Hi All,
    Is there is any functionality in Controlling which can compare the costing for two FERT materials.
    or
    is there is  any functionality where we can compare two material price with reference to BOM in controlling
    Please help me to compare the material price with reference to BOM
    Regards
    nandu

    Hi,
    You can use this report to compare two itemizations. The report compares the characteristics item number, item category, cost element, resource, material, cost center, plant/work center, cost center/activity type, operation number, BOM item, assembly indicator, and cost component.
    You can access this report as follows:
    Accounting ® Controlling ® Product Cost Controlling ® Product Cost Planning ® Material Costing ® Cost Estimate with Quantity Structure or Cost Estimate Without Quantity Structure ® Compare
    or
    Accounting ® Controlling ® Product Cost Controlling ® Product Cost Planning ® Information System ® Object Comparisons ® For Material ® Itemization Comparison.
    For Detail Please reffer following link:
    http://help.sap.com/saphelp_46c/helpdata/en/56/abd108f1a611d28a950000e8214595/content.htm
    Thanks and Regards
    Binoj M D

  • Compare two mail message

    I am writing an application to download mail messages from some other pop3/imap mail servers to the folder that created at default imap server.
    I want to compare the message get from server and current messages inside the folder, so I don't get the duplicates. How do I compare two Message object?
    Thanks in advance!

    The way I will do it is to creat a new class that extends java.mail.Message. In such a subclass, one can override "equal" method to compare the data within.

  • Comapring two Calender Objects  for same Date object

    hi,
    I am having problem with Comparing two Calender Objects which is having same Date value but time stamp is not same.when i printed as Calender.getTime()---->i found them as.
    Cal1----->Wed Feb 28 20:26:29 IST 2007
    Cal2------>Wed Feb 28 00:00:00 IST 2007
    Now the method:
    While(Cal1.getTime().compareTo(Cal2.getTime()) ==0 ) is Evaluating false.
    i dont want to be concerned with time stamp.i want condition to be true.
    Please help me .thx in advance.
    Cheers
    Akash

    My comment was directed at the fact that you gave the same answer I did, only faster. There is no other way I am aware of that will be any quicker. Of course, that is looking at a small piece of code out of context, so there may well be a better way.
    ~Tim
    Message was edited by:
    SomeoneElse

  • Problem with XMLEncoder for complex java object i

    Hi All.
    My problem with XMLEncoder is it doesnt transfrom java objects without default no arguement constructor. I was able to resolve this in my main java object class, by setting a new persistence delegate, but for other classes that are contained in the main class, they are not being encoded.
    Thanks in advance for your answers

    Better to put this in java forum :-)
    Just check, if this helps.
    http://forum.java.sun.com/thread.jspa?threadID=379614&messageID=1623434

  • 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.

Maybe you are looking for