Comparing two ResultSets for equality

Hello,
I wish to test if two separate ResultSet objects are identical.
By identical I mean that two different ResultSet objects are identical if
they contain the same rows in the same order, and each row contains identical values in the two ResultSets.
Two possibilities could be that the equals() method returns true or that the hashcode() method also produces the same hash value if the objects are identical as described.
I haven't been able to find any documentation on this issue.
Does anyone know if either (or both) of these methods have the contract as described above? If so are they guaranteed?
I can see several potential problems here. Performance with a large ResultSet, duplicate rows, and the ordering of rows not being guaranteed?
Thanks in advance.
Tim

Two possibilities could be that the equals() method
returns true or that the hashcode() method also
produces the same hash value if the objects are
identical as described.I can tell you without looking anything up that these methods do not do that, as doing that would require them to scan the entire result-set, and JDBC tries to avoid doing useless processing. You are going to have to write this code yourself.

Similar Messages

  • How compare two URLs for equality if one uses jar protocol?

    I'm trying to see if some URLs are referring to the same jar file but some of them come with the prepend/append of "jar:file:/" and "!/" and some are just as "file:/". So when I call "URL.equals(...)", it returns false. How do I properly compare these two?
    //Returns false, even though both can be used to find the jar file
    new URL( "jar:file:/home/me/tmp.jar!/" ).equals( new URL( "file:/home/me/tmp.jar" ) );

    The URL with the leading "jar:" and trailing "!/" is a JAR URL. It's described in the JarURLConnection class API document.
    This is one way (there any be a simpler one). You will have to figure out whether you're working with a jar URL or a "regular" URL by parsing the URL to figure out which kind it is. One diffrence is the leading "jar"
    import java.io.IOException;
    import java.net.JarURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    public class Xy
        public static void main(String[] args)
            throws MalformedURLException, IOException
            URL fileURL =
                new URL("file:/Program Files/Java/jre6/lib/deploy.jar");
            URL jarURL =
                new URL("jar:file:/Program Files/Java/jre6/lib/deploy.jar!/");
            String fURL = fileURL.toString();
            System.out.println("fileURL: " + fURL);
            String jURL = ((JarURLConnection) jarURL.openConnection()).
                getJarFileURL().toString();
            System.out.println("jarURL: " + jURL);
            if (fURL.equals(jURL))
                System.out.println("They are equivalent");
    }

  • ??how to compare two resultsets??

    hi all!
    i need to find out whether two resultsets contain the same data.
    the only way i know how to do it in java is to put them into a while loop and fetch the contents first and then compare the contents.
    but is there an easier way to compare resultsets?
    does anyone know how to compare two resultsets without extracting the data?
    the code example here executes two identical queries on an oracle database, compare and print the resultsets.
    public ResultSet getResultset(String query)
    ResultSet rs=null;
    try { rs=Stmt.executeQuery(query); }
    catch(Exception e) { e.printStackTrace(); }
    return rs;
    public static void main(String[] args) {
    ResultSet r1=null;
    ResultSet r2=null;
    try {
    database db = new ddatabase();
    r1=db.getResultset("Select 'name' from person");
    r2=db.getResultset("Select 'name' from person");
    if (r1 == r2) {
    System.out.println("ok");
    System.out.print(r1);
    System.out.println();
    System.out.print(r2);
    else {
    System.out.println("not ok");
    System.out.print(r1);
    System.out.println();
    System.out.print(r2);
    jdbc.cleanup();
    catch(Exception e) {e.printStackTrace();}
    and here is the output:
    F:\java rs_compare
    not ok
    oracle.jdbc.driver.OracleResultSetImpl@4413ee
    oracle.jdbc.driver.OracleResultSetImpl@786e64
    as you can see the resultsets are different though the data they contain have to be the same.
    so the 'if(resultset#1 == resultset#2)' does not work.
    thanks for any help
    best regards
    5ithl0rd

    Don't cross-post.
    I'll bet ResultSet implementations don't override equals() to provide "deep equals" behavior, in which case it'll be no different than using "==".
    It's a bad idea to compare two ResultSets this way. You'll have to load both into objects or data structures and compare those in a "deep" way.
    Besides, the ONLY way two ResultSets could be different, given the same query, would be if there were multiple clients that could write to the table between queries and change the underlying data. If your two queries are sufficiently isolated, I'd say that the same query will return the same ResultSet.
    %

  • Compare two XMLElements for semantical equality

    I rewrote a statement that generates XML from our database and I need to check if it produces the same result as the old statement. However, for some reason, the new statement generates a certain empty element as <FOO/> while the old statement generates a <FOO></FOO>. The strange thing is, that the tag is generated by a substatement that definitely has not changed at all.
    This wouldn't be a problem if I could compare the two XMLElements for semantical equality but I couldn't find an appropriate function.

    I didn't change the database version, both versions of my XML generating queries run on the same schema on the same database. I think it doesn't make sense to post the whole queries since they are really huge. So I will try to point out the relevant part:
    I have a rather complex query that generates an XML document using SQL/XML. I refactored that query to avoid code redundancies and to make it more readable. The output of the refactored query is the same as that of the old query, except for the representation of that empty tag.The empty tag is generated by a subquery that is called by the refactored query. The subquery has not changed at all and it is called with the same parameters as before.
    I don't know if there is a way to take explicit control of how empty tags should be represented. But it seems that the representation that the DBMS chooses by default is practically not predictablae.

  • Comparing two ResultSet

    Hi Everybody,
    Can anybody tell me is there any method to compare the contents of two ResultSets and decide whether they are same or not.
    Thanks

    Yes,
    Create a method that takes the two result sets, get the metada of the table and compare field by fiel.
    Another alternative is to copy the ResultSet to a Vector and than compare it.
    HTH
    Trajano Roberto

  • Compare two strings for partial or full match

    I have been trying to figure out away of comparing two strings.
    I can get the full string matching to successfully work but am struggling on how to get partial eg wildcard search working.
    say I had names like paul Duncan, George Morrison.
    I have split them up so its now paul , duncan i then use the users entered string to compare it against the name name to see if it matches anything in the first name or the last name if it does i added it to an arraylist.
    however i have tried t use a indexof as i believe this looks for similarity (Substring matches?) but it always returns -1.
    Could anyone possibly direct me to a method that will allow me to use partial text string to match it against stored user names.
    eg user enters pa
    I would return anything that would contain pa
    thanks for any help

    thank you for the reply
    Sorry I forgot to put in the code.
    This is a reduced down version including the read in from a text file as well as the index of if statement and the adding of it to an array list.
    public class FindContact {
    String res;
    /** Creates a new instance of FindContact */
    public FindContact() {
    public Object[] FindAUser(String passSearch) {
    System.out.println("getting here");
    ArrayList found = new ArrayList();
    String patternStr = ",";
    int j, i = 0;
    try {
    BufferedReader in = new BufferedReader(new FileReader("H:\\out.txt"));
    String str;
    while ((str = in.readLine()) != null) {
    String[] fields = str.split(patternStr);
    //for(j=0;j < fields.length;j++) {
    if (fields.length != 0) {
    if (passSearch.indexOf(fields[0])!=-1 || passSearch.indexOf(fields[1])!=-1) {
    found.add(str);
    System.out.println("ENDDDDDDDD value ");
    in.close();
    } catch (IOException e) {
    System.out.println(e.toString());
    Object[] foundResult = new Object[found.size()];
    foundResult = found.toArray();
    if (foundResult.length >= 0) {
    System.out.println(foundResult.length);
    return foundResult;
    Hope that helps as it has confused me and am not sure why it is not returning a value.
    Should I maybe use the contain method instead to search for the user inputted string?

  • How to Compare Two Strng without .equals() method

    Hiii,
    How to compare two Strings with out .equals method if there are white spaces in between these string it should be avoided..
    eg: ab cd ef g is equal to a bc de fg
    Please give me the logic or code..
    Your help will be appreciated

    dude find the code without the equal method
    public class test {     
         public static void main(String args[])
              String str = "ab cd ef g" ;
              String str1 = "a bc de fg";
              char []ch = str.toCharArray();
              char []ch1 = str1.toCharArray();
              int counter =0, counter1 = 0;
              while(counter < ch.length && counter1 < ch1.length)
                   while(ch[counter]==' ')
                        counter++;
                   while(ch1[counter1]==' ')
                        counter1++;
                   if(ch[counter] != ch1[counter1])
                        break;
                   counter++; counter1++;
              if(counter == ch.length && counter1 == ch1.length)
                   System.out.println("true");
              else
                   System.out.println("false");
    }

  • Comparing array elements for equality

    Hi
    I have written a simple program that works as a lottery number predictor. It works fine except for the fact that sometimes 2 numbers will be the same. Does anyone know of a method that compares an array element to the others to test for equality?

    ok I've had a go at implementing a solution. I worked it out on paper so I haven't tested it yet in the program. Let me know if you can see any errors that I can't.
       boolean numNotSame = true;
       int[] lottery = new int[5];
       int currentNumber;
       start:  //label to return to if 2 numbers are the same
       while(numNotSame){
          for( int j = 0; j < lottery.length; j++){
              currentNumber = 1 + randomNumbers.nextInt(34);   //get random number
              for( int i = 0; i < lottery.length; i++){
                 if( currentNumber == lottery)
    continue start; //if numbers are the same begin again
    } //end inner for
    lottery[ j ] = currentNumber; //set array element if number not used yet
    } //end outer for loop
    numNotSame = false; //set false so while loop will end
    } //end while block

  • How to compare two recordsets for common or difference or join (ASP)

    Good day,
    I have Adobe Dreamweaver CS3 and here is my question. I have created two recordsets, one called Active_Stu and the other is called Active_Emps. One deals with active employees and the other deals with active Students. Both hava ids of students and employees. The student id field is called stuid and the employee id field in the active employee record set is called empid. They are both integers and come from one table. Each recordset is a SQL query that work fine on its own. How can I join the two recordsets into a third recordset? How can I find the ids in one that is not in the other one? or the ones that both have in common? I can do all that in Access by bringing the two queries into the third one and do a left join or others but not sure how to do such action in the Dreamweaver.
    I am using VB ASP for my development.
    Any ideas?

    Don't try to join two recordsets to find rows different or in common between tables. You do the same as you would in Access. Just write a single SQL query that joins the tables. Depending on what exactly you are looking for, you would use inner joins, outer joins or sub-selects.

  • Compare two arrays (greater-equal) has wrong result. Bug?

    Hallo,
    in my attached example (LX 8.2) i have three arrays which are displayed in the graph.
    As you can see the "Trace-plot" is below the "LowerLimit-plot".
    In the code i do a "Trace >= LowerLimit" which should have the result = FALSE because its not always >=.
    But the result is TRUE!!
    Why??
    All three arrays have 201 points
    Thanks for your help
    Attachments:
    TraceTest.vi ‏19 KB

    It is only recording the last point saved from the comparison.  Try This:
    Message Edited by Tom Haggerty on 12-04-2007 08:50 AM
    Message Edited by Tom Haggerty on 12-04-2007 08:51 AM
    Sorry about the hidden wires!  I just added the FOR loop very quickly and didn't clean it up.
    Tom
    Message Edited by Tom Haggerty on 12-04-2007 08:52 AM
    Attachments:
    fix.PNG ‏11 KB

  • Comparing dates for equality using API

    Hello,
    I was wondering if you could help me understand if it is possible for me to compare two dates for equality.
    I am looking to only compare the date and the month. So, if I am checking "today" with another objects Date for equality, it obviously fails because the compareTo and the equals method of both Date and Calendar, I think, are comparing even the timestamps.
    here is something I wrote for testing, which obviously is of no use
    Calendar today = Calendar.getInstance();
    Calendar later = Calendar.getInstance();
    later.set(Calendar.HOUR, 03);
    System.out.println(today.getTime());
    System.out.println(later.getTime());
    if(today.equals(later)){
       System.out.println("BIG BANG");
    if(today.compareTo(later)<0)
       System.out.println("Today Date is Lesser than my Date");
    else if(today.compareTo(later)>0)
       System.out.println("Today Date is Greater than my date");
    else
       System.out.println("Both Dates are equal");   
    Date today = new Date();
    Date myDate = new Date();
    myDate.setHours(23);
    System.out.println(today);
    System.out.println(myDate);
    if(today.compareTo(myDate)<0)
       System.out.println("Today Date is Lesser than my Date");
    else if(today.compareTo(myDate)>0)
       System.out.println("Today Date is Greater than my date");
    else
       System.out.println("Both Dates are equal");   
       So is then the only way left, is using the simple date formatter and going about things ?

    package forums;
    import java.util.Calendar;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    public class CalendarExample
      private static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd");
      public static void main(String[] args) {
        Calendar today = Calendar.getInstance();
        Calendar later = Calendar.getInstance();
        later.set(Calendar.HOUR, 3);
        System.out.println("today="+DF.format(today.getTime()));
        System.out.println("later="+DF.format(later.getTime()));
        System.out.println("isSameDayAndMonth(today, later) = "+isSameDayAndMonth(today, later));
        System.out.println("\n");
        Calendar tomorrow = Calendar.getInstance();
        tomorrow.set(Calendar.DATE, tomorrow.get(Calendar.DATE)+1);
        System.out.println("today="+DF.format(today.getTime()));
        System.out.println("tomorrow="+DF.format(tomorrow.getTime()));
        System.out.println("isSameDayAndMonth(today, tomorrow) = "+isSameDayAndMonth(today, tomorrow));
        System.out.println("\n");
      public static boolean isSameDayAndMonth(Calendar a, Calendar b) {
        return a.get(Calendar.DATE) == b.get(Calendar.DATE)
            && a.get(Calendar.MONTH) == b.get(Calendar.MONTH)
    }You're welcome... Javas standard date libraries leave a lot be desired. I recommend you try Joda, which is [a long standing JSR, which has never gotten up|http://www.theserverside.com/news/thread.tss?thread_id=44248].

  • Compare tables in two schemas for the table with particular column & value

    Hello All,
    I have a query to find out the list of table from a given schema to extract all the tables having a search column .
    ex :
    SELECT OWNER, TABLE_NAME, COLUMN_NAME FROM
    ALL_TAB_COLUMNS WHERE OWNER='<SCHEMA_NAME>'
    AND COLUMN_NAME='<COLUMN_NAME>'
    I want to compare two schemas for the same above query .
    Can we wirte a query on this - I am using SQL DEVELOPER , which has menu item - TOOL - database differneces to find the diffenence between two schemas but my requirement is to find the differences in two schemas for all the tables matching for a particular column ( as given in quer).
    Appreciate your help.
    thanks/Kumar
    Edited by: kumar73 on 29 Nov, 2012 1:50 PM

    Hi, Kumar,
    This is the SQL and PL/SQL forum. If you have a question about SQL Developer, then the SQL Developer is a better place to post it. Mark this thread as "Answered" before starting another thread for the same question.
    If SQL Developer has a tool for doing what you want, don't waste your time trying to devise a SQL solution. The SQL Developer way will probably be simpler, more efficient and more reliable.
    If you do need to try a SQL solution, then post some sample data (CREATE TABLE and INSERT statements for a table that resembles all_tab_columns; you can call it my_tab_columns) and the results you want from that data.

  • Comparing two Calendar dates

    No question. Just a comment with code example.
    Yesterday I was having issues comparing two Calendar dates. They looked equal in my println statement, but they failed the test. The solution evaded my cafeine intensified brain for hours. Then it hit me. Print out the time in milliseconds and see if the numbers were the same. Nope. Why?
    The problem was that in the real world, you get dates from all over the place, not just cooked up for a text book example. (Don't you just hate those text book examples in their unrealistic world?) Anyway, I was getting a date from an HTML form and a data from a database and comparing the two once I had converted them both to a Calendar object. This seemed a reasonable choice.
    Well, the java.sql.Date that the Oracle driver returned which was converted to a java.util.Date was fine. I ran this into a Calendar with the call calS.setTime(dbDate). The form date was split into fields and put into a difference Calendar obj with the call calF.set(fYear, fMonth, fDay, 0, 0, 0). This too seemed reasonable. Then a call to calS.equls(calF) resulted in a false even though the actual dates were in fact the same.
    The problem was with the time. The java.sql.Date (calS) had a time of 00:00:00 which was fine. The calendar from the form also had 00:00:00 for a time since I initialized it with zeros. Hummmmm. Now what? As mentioned before, I decided to print out the actuall time in milliseconds and that gave me my answer. The two calendars were off by only milliseconds, but that's why. You see, the equals method of Calendar compares two dates/time in milliseconds. You can see this in the source for yourself. It's not difficult to read at all. Download and open the api source file, src.zip, and locate Calendar.java in the java.util directory.
    The fix was to add calF.set(Calendar.MILLISECOND, 0) and calS.set(Calendar.MILLISECOND, 0) to zero out the milliseconds in each Calendar object. That did the trick. Here's example code of the problem (test1) and the solution (test2). I tried to simulate as close to real world as possible. If you have a better solution or I've made some error, please let me know. I'm always looking for better ways.
    Main.java
    import java.util.Calendar;
    import java.util.Date;
    import java.text.SimpleDateFormat;
    public class Main {
        private int fYear = 2003;
        private int fMonth = 3;  // march
        private int fDay = 14;
        public static void main(String[] args) {
            Main main = new Main();
            main.test1();
            main.test2();
        public void test1() {
            SimpleDateFormat df = new SimpleDateFormat();
            // get the date from the form
            Calendar calF = Calendar.getInstance();
            calF.set(fYear, fMonth-1, fDay, 0, 0, 0);  // month starts at 0 - so march would be 2
            System.out.println("From form date:     [" + df.format(calF.getTime()) + "] [" + calF.getTimeInMillis() + "]");
            // simulate other activity in the app
            try {
                Thread.sleep(5000);
            catch (Exception ex) {
                ex.printStackTrace();
            // get the Date from the shared object which comes from a database (java.sql.Date)
            // the return is java.util.Date
            // convert to a Calendar
            SharedObject so = new SharedObject();
            Date myDate = so.getTheDate();
            Calendar calS = Calendar.getInstance();
            calS.setTime(myDate);
            System.out.println("Shared Object date: [" + df.format(calS.getTime()) + "] [" + calS.getTimeInMillis() + "]");
            // compare the two calendars for equality
            if (calS.equals(calF)) {
                System.out.println("The same");
            else {
                System.out.println("NOT the same");
        public void test2() {
            SimpleDateFormat df = new SimpleDateFormat();
            // get the date from the form
            Calendar calF = Calendar.getInstance();
            calF.set(fYear, fMonth-1, fDay, 0, 0, 0);
            calF.set(Calendar.MILLISECOND, 0);  // the magic bean
            System.out.println("From form date:     [" + df.format(calF.getTime()) + "] [" + calF.getTimeInMillis() + "]");
            // simulate other activity in the app
            try {
                Thread.sleep(5000);
            catch (Exception ex) {
                ex.printStackTrace();
            // get the Date from the shared object which comes from a database (java.sql.Date)
            // the return is java.util.Date
            // convert to a Calendar
            SharedObject so = new SharedObject();
            Date myDate = so.getTheDate();
            Calendar calS = Calendar.getInstance();
            calS.setTime(myDate);  // just to be safe
            calF.set(Calendar.MILLISECOND, 0);
            System.out.println("Shared Object date: [" + df.format(calS.getTime()) + "] [" + calS.getTimeInMillis() + "]");
            // compare the two calendars for equality
            if (calS.equals(calF)) {
                System.out.println("The same");
            else {
                System.out.println("NOT the same");
    SharedObject.java
    public class SharedObject {
        public java.util.Date getTheDate() {
            java.util.Date d = null;
            try {
                java.sql.Date s = java.sql.Date.valueOf("2003-3-14");  // this march is converted internally
                d = (java.util.Date)s;
            catch (Exception ex) {
                ex.printStackTrace();
            return d;
    } The output
    From form date:     [3/14/03 12:00 AM] [1047621600296]
    Shared Object date: [3/14/03 12:00 AM] [1047621600000]
    NOT the same
    From form date:     [3/14/03 12:00 AM] [1047621600000]
    Shared Object date: [3/14/03 12:00 AM] [1047621600000]
    The same

    So your post boils down to the fact that Calendar's set(year, month, day, hour, minute, second) method doesn't change the milliseconds fraction?
    Given that there is this method, I guess it would be nice if there was a method that simultaneously set all fields, but the API does state:
    Previous values of other fields are retained. If this is not desired, call clear() first.

  • Comparing layers for equality

    Is it possible to compare two different layers to see if they are in fact the same image?
    I'm actually working on a game at the moment. The game map was created by using game sprites created by other people. For example, I found 5 different pictures of trees, and copy pasted them into photoshop multiple times to create a forest. I have 100 trees in my photoshop document, but in reality, they are all made up of only 5 images. I want to save out each of these trees into a format usable by my game engine. I want to save each layer as an image, but avoid saving duplicates. Thus the need to compare layers for equality.
    Is it possible to do this within a photoshop script? Thanks for any help you can provide.

    but wouldn't this only work in the instance of them being on top of each other?
    That bit of code presumes:
    The layers are in the same document
    The layers are the only two layers visible
    The content of the layers is aligned.
    The layers have simple content (no layer masks, vector masks, layer styles)
    There may be other assumptions that I'm making, but this is all that I can think of.
    For the trees/forest problem, I would iterate though the tree-layers.
    Create a new document that is as large as the largest tree-layer in the forest.
    Hide the background layer.
    Copy the first layer to the new document.
    Copy the second layer to the new doc
    Do the layer comparison code from above my previous post
    If the layers are the same, delete the new one.
    Go to the next layer in the forest document.
    Copy and compare the new layer against each layer in the new document.
    Delete it if it's a dupe.
    When you're done, the new document should have only the unique trees.

  • Comparing objects for equality with UDT's

    Hi.
    I was wondering how Oracle does comparison for equality of objects that contains parameters of user defined types.
    Suppose I have an object with a parameters whose types are:
    1) number,
    2) varchar2,
    3) nested table type,
    4) associative array
    and I want to compare two such objects for equality. Would Oracle compare all parameters of this 2 compared objects field-by-field (and dig recursive to "leafs"), or would it compare only 1), 2) and doas nothing with 3) and 4)?
    Must I declare an order method for such comparison?

    You didn't specify a version - this is correct for 10.2, I'm not sure if it has changed in 11g.
    By default it will compare for exact equality - i.e that every attribute is the same. You can also only do it in SQL, not PL/SQL. Also can only do = and <> - you cannot do < or > etc.
    You need to create a MAP or ORDER method on the type to do any more sophisticated comparison (Same as in most object oriented languages). Documentation is here http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14260/adobjbas.htm#sthref211

Maybe you are looking for