Differencebetween These Two Comparisons

What is the difference between these two comparisons in PHP?

The php documentation on Comparison Operators tells us that != and <> in fact do the same.

Both are named “Not Equal”,
and are described as:

TRUE if $a is not equal to $b after type juggling.

Most people use != though, as that is more conforming to other programming languages which do/may not support <>. In fact, I don’t remember seeing <> being used in any PHP code yet.

Why do these two comparisons have different results?

Because new Byte() creates value type, which are compared by value (by default it will return byte with value 0). And new Byte[0] creates array, which is a reference type and compared by reference (and these two instances of array will have different references).

See Value Types and Reference Types article for details.

What is the difference between compare() and compareTo()?

From JavaNotes:

  • a.compareTo(b):

    Comparable interface : Compares values and returns an int which tells if the values compare less than, equal, or greater than.

    If your class objects have a natural order, implement the Comparable<T> interface and define this method. All Java classes that have a natural ordering implement Comparable<T> - Example: String, wrapper classes, BigInteger

  • compare(a, b):

    Comparator interface : Compares values of two objects. This is implemented as part of the Comparator<T> interface, and the typical use is to define one or more small utility classes that implement this, to pass to methods such as sort() or for use by sorting data structures such as TreeMap and TreeSet. You might want to create a Comparator object for the following:

    • Multiple comparisons. To provide several different ways to sort something. For example, you might want to sort a Person class by name, ID, age, height, ... You would define a Comparator for each of these to pass to the sort() method.
    • System class To provide comparison methods for classes that you have no control over. For example, you could define a Comparator for Strings that compared them by length.
    • Strategy pattern To implement a Strategy pattern, which is a situation where you want to represent an algorithm as an object that you can pass as a parameter, save in a data structure, etc.

If your class objects have one natural sorting order, you may not need compare().


Summary from http://www.digizol.com/2008/07/java-sorting-comparator-vs-comparable.html

Comparable
A comparable object is capable of comparing itself with another object.

Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances.


Use case contexts:

Comparable interface

The equals method and == and != operators test for equality/inequality, but do not provide a way to test for relative values.

Some classes (eg, String and other classes with a natural ordering) implement the Comparable<T> interface, which defines a compareTo() method.

You will want to implement Comparable<T> in your class if you want to use it with Collections.sort() or Arrays.sort() methods.

Defining a Comparator object

You can create Comparators to sort any arbitrary way for any class.

For example, the String class defines the CASE_INSENSITIVE_ORDER comparator.


The difference between the two approaches can be linked to the notion of:

Ordered Collection:

When a Collection is ordered, it means you can iterate in the collection in a specific (not-random) order (a Hashtable is not ordered).

A Collection with a natural order is not just ordered, but sorted. Defining a natural order can be difficult! (as in natural String order).


Another difference, pointed out by HaveAGuess in the comments:

  • Comparable is in the implementation and not visible from the interface, so when you sort you don't really know what is going to happen.
  • Comparator gives you reassurance that the ordering will be well defined.

Which equals operator (== vs ===) should be used in JavaScript comparisons?

The strict equality operator (===) behaves identically to the abstract equality operator (==) except no type conversion is done, and the types must be the same to be considered equal.

Reference: Javascript Tutorial: Comparison Operators

The == operator will compare for equality after doing any necessary type conversions. The === operator will not do the conversion, so if two values are not the same type === will simply return false. Both are equally quick.

To quote Douglas Crockford's excellent JavaScript: The Good Parts,

JavaScript has two sets of equality operators: === and !==, and their evil twins == and !=. The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and !== produces false. The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to coerce the values. the rules by which they do that are complicated and unmemorable. These are some of the interesting cases:

'' == '0'           // false
0 == '' // true
0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false
null == undefined // true

' \t\r\n ' == 0 // true

Equality Comparison Table

The lack of transitivity is alarming. My advice is to never use the evil twins. Instead, always use === and !==. All of the comparisons just shown produce false with the === operator.


Update:

A good point was brought up by @Casebash in the comments and in @Phillipe Laybaert's answer concerning objects. For objects, == and === act consistently with one another (except in a special case).

var a = [1,2,3];
var b = [1,2,3];

var c = { x: 1, y: 2 };
var d = { x: 1, y: 2 };

var e = "text";
var f = "te" + "xt";

a == b // false
a === b // false

c == d // false
c === d // false

e == f // true
e === f // true

The special case is when you compare a primitive with an object that evaluates to the same primitive, due to its toString or valueOf method. For example, consider the comparison of a string primitive with a string object created using the String constructor.

"abc" == new String("abc")    // true
"abc" === new String("abc") // false

Here the == operator is checking the values of the two objects and returning true, but the === is seeing that they're not the same type and returning false. Which one is correct? That really depends on what you're trying to compare. My advice is to bypass the question entirely and just don't use the String constructor to create string objects from string literals.

Reference
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3

Comparing two dictionaries and checking how many (key, value) pairs are equal

If you want to know how many values match in both the dictionaries, you should have said that :)

Maybe something like this:

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print(len(shared_items))

How to get the difference between two dictionaries in Python?

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

Compare two numbers if the difference is higher/lower than 'x', do something

If you want the amount to check by a certain amount, change your condition to this:

if (second - first > 0.5)
{
cout << "Too Big!\n";
}
else if (second - first < 0.5)
{
cout << "Too low\n";
}

This would check if the difference between the 2 nunbers fits the criteria you want. Also, change the types of your numbers to double, since currently truncation will compare the wrong numbers. For example in checking the value with a variable, try this:

int main()
{

double first = 0;
double second = 0;
double x = 0;
cin >> first;
cin >> second;
cin >> x;
if (second - first > x) {
cout << "Too Big!\n";
}
else if (second - first < x) {
cout << "Too low\n";
}
else {
cout << "Calculation will be made\n";
}

return 0;
}


Related Topics



Leave a reply



Submit