Comparing Objects using ByteArrays

Other day I was thinking in this class I have seen.

Simple compare 2 objects by generating a ByteArray from themselves and compare with the other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package {
              import flash.utils.ByteArray;
              public class ObjectTools {
                      public function ObjectTools () {
                      }
                      /**
                       * Compares two objects and checks if they are identical. Does not compare the objects by reference,
                       * but compares to see if the values of the properties are identical.
                       *
                       * @param obj1
                       * @param obj2
                       *
                       * @return
                       */

                      public static function compare (obj1:Object, obj2:Object):Boolean {
                              var b1:ByteArray = new ByteArray();
                              var b2:ByteArray = new ByteArray();
                              b1.writeObject(obj1);
                              b2.writeObject(obj2);

                              // compare the lengths first
                              var size:uint = b1.length;
                              if (b1.length == b2.length) {
                                      b1.position = 0;
                                      b2.position = 0;
                                      // then the bits
                                      while (b1.position < size) {
                                              var v1:int = b1.readByte();
                                              if (v1 != b2.readByte()) {
                                                      return false;
                                              }
                                      }
                              }
                              if (b1.toString() == b2.toString()) {
                                      return true;
                              }
                              return false;
                      }
              }
      }

From: http://blog.joshbuhler.com/2008/02/11/comparing-objects-using-bytearrays/

Comment are closed.