I have the following code:   public class Porow{     public static void main (String[] args){         String s1 = "foo";         String s2 = "foo";          System.out.println(s1 == s2);         System.out.println(s1.equals(s2));          String s3 = new String ("foo");         System.out.println(s1 == s3);         System.out.println(s1.equals(s3));     } }   which outputs:   true true false true   I am trying to understand and explain what's going on here. And I need some guidance. Will I be right to say s1 and s2 are same objects stored in different parts of memory and that's why we get the first 2 trues?   Why is the 3rd output false? is s3 a different object? and why does it produce true with the equals method on s1? I'd appreciate some help. Thanks :).  EDIT:  This question is not about == nor equals() I know what they are. My question is more related to memory references and addresses. So don't just presume I'm asking about String Comparison. I'm asking about a whole different thing here.
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
87341
An array is defined to be maxmin equal if it contains at least two different elements and the number of times the maximum value occur is the same as the number of times the minimum value occur. So {11, 4, 9, 11, 8, 5 , 4, 10} is maxmin equal, because the max value 11 and min value 4 both appear two times in the array.   if the input array is {} , isMaxMinEqual should return false (array must have at least two different elements) status = false; if the input array is {2}, isMaxMinEqual should return false (array must have at least two different elements). if the input array is {1,1,1,1,1,1}, isMaxMinEqual should return false (array must have at least two different elements).  if the input array is {2,4,6,8,11}, isMaxMinEqual should return true (Both max value(11) and min value 2 appear exactly one time). if the input array is {-2,-4,-6,-8,-11}, isMaxMinEqual should return true(Both max value(-2) and min value -11 appear exaclty one time).   I wrote the class MaxMin which satisfied the above condition.  public class MaxMin {  public static void main(String args[]) {     System.out.println("The result is: " + isMaxMinEqual(new int[]{2, 2})); }  public static boolean isMaxMinEqual(int[] a) {     boolean status = false;     int count = 0;     if (a.length &lt; 2) {         status = false;         return status;     }     for (int i = 1; i &lt; a.length; i++) {         if (a[i - 1] != a[i]) {             count++;         }     }      int max = a[0];     int min = a[0];     for (int i = 0; i &lt; a.length; i++) {         if (a[i] &gt; max) {             max = a[i];         } else if (a[i] &lt; min) {             min = a[i];         }     }      int maxCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == max) {             maxCount++;         }     }      int minCount = 0;     for (int j = 0; j &lt; a.length; j++) {         if (a[j] == min) {             minCount++;         }     }     System.out.println(count);     System.out.println("max is: " + max);     System.out.println("min is: " + min);     System.out.println("Max Count is: " + maxCount);     System.out.println("Min Count is: " + minCount);      if (maxCount == minCount &amp;&amp; count &gt;= 1) {         status = true;     }      return status; } }
21022
I would like to compare the contents of a couple of collections in my Equals method.  I have a Dictionary and an IList.  Is there a built-in method to do this?  Edited: I want to compare two Dictionaries and two ILists, so I think what equality means is clear - if the two dictionaries contain the same keys mapped to the same values, then they're equal.
4461
This prints 83  System.out.println(0123)   However this prints 123  System.out.println(123)   Why does it work that way?
40567
I'm working on a project where i find i'm checking for the following in many, many places:  if(item.Rate == 0 || item.Rate == null) { }   more as a curiousity than anything, what's the best way to check for both cases?  I've added a helper method which is:  public static bool nz(object obj) {     var parsedInt = 0;     var parsed = int.TryParse(obj.ToString(), out parsedInt);     return IsNull(obj) || (parsed &amp;&amp; parsedInt == 0); }   Is there a better way?
12823
In .NET, what is the difference between String.Empty and "", and are they interchangable, or is there some underlying reference or Localization issues around equality that String.Empty will ensure are not a problem?
29117
So I was playing around the other day just to see exactly how mass assignment works in JavaScript.  First I tried this example in the console:  a = b = {}; a.foo = 'bar'; console.log(b.foo);   The result was "bar" being displayed in an alert. That is fair enough, a and b are really just aliases to the same object. Then I thought, how could I make this example simpler.  a = b = 'foo'; a = 'bar'; console.log(b);   That is pretty much the same thing, isn't it? Well this time, it returns foo not bar as I would expect from the behaviour of the first example.  Why does this happen?  N.B. This example could be simplified even more with the following code:    a = {}; b = a; a.foo = 'bar'; console.log(b.foo);  a = 'foo'; b = a; a = 'bar'; console.log(b);     (I suspect that JavaScript treats primitives such as strings and integers differently to hashes. Hashes return a pointer while "core" primitives return a copy of themselves)
13221
&quot;foo&quot; instanceof String //=&gt; false &quot;foo&quot; instanceof Object //=&gt; false  true instanceof Boolean //=&gt; false true instanceof Object //=&gt; false false instanceof Boolean //=&gt; false false instanceof Object //=&gt; false  12.21 instanceof Number //=&gt; false /foo/ instanceof RegExp //=&gt; true  // the tests against Object really don't make sense  Array literals and Object literals match... [0,1] instanceof Array //=&gt; true {0:1} instanceof Object //=&gt; true  Why don't all of them? Or, why don't they all not? And, what are they an instance of, then? It's the same in FF3, IE7, Opera, and Chrome. So, at least it's consistent.
41144
As made clear in update 3 on , this notation: var hash = {}; hash[X]  does not actually hash the object X; it actually just converts X to a string (via .toString() if it's an object, or some other built-in conversions for various primitive types) and then looks that string up, without hashing it, in &quot;hash&quot;. Object equality is also not checked - if two different objects have the same string conversion, they will just overwrite each other. Given this - are there any efficient implementations of hashmaps in JavaScript? (For example, the second Google result of  yields an implementation which is O(n) for any operation. Various other results ignore the fact that different objects with equivalent string representations overwrite each other.
17016
The following  code is supposed to compare two strings or variables. But, I cannot do it. Here, output doesn't depend upon the changing of inputs. Can anyone correct this code?    #!/bin/sh   echo "Enter your username1:"   read username1   echo "Enter your username2:"   read useraname2   if [ "$username1"=="$username2" ]   then   echo 'Same'   else   echo 'Different'   fi
2525
My  has failed me.  In Python, are the following two tests for equality equivalent?  n = 5 # Test one. if n == 5:     print 'Yay!'  # Test two. if n is 5:     print 'Yay!'   Does this hold true for objects where you would be comparing instances (a list say)?  Okay, so this kind of answers my question:  L = [] L.append(1) if L == [1]:     print 'Yay!' # Holds true, but...  if L is [1]:     print 'Yay!' # Doesn't.   So == tests value where is tests to see if they are the same object?
105864
Say for a Point2 class, and the following Equals:  public override bool Equals ( object obj )  public bool Equals ( Point2 obj )   This is the one that is shown in the Effective C# 3:  public override bool Equals ( object obj ) {     // STEP 1: Check for null     if ( obj == null )     {         return false;     }      // STEP 3: equivalent data types     if ( this.GetType ( ) != obj.GetType ( ) )     {         return false;     }     return Equals ( ( Point2 ) obj ); }  public bool Equals ( Point2 obj ) {     // STEP 1: Check for null if nullable (e.g., a reference type)     if ( obj == null )     {         return false;     }     // STEP 2: Check for ReferenceEquals if this is a reference type     if ( ReferenceEquals ( this, obj ) )     {         return true;     }     // STEP 4: Possibly check for equivalent hash codes     if ( this.GetHashCode ( ) != obj.GetHashCode ( ) )     {         return false;     }     // STEP 5: Check base.Equals if base overrides Equals()     System.Diagnostics.Debug.Assert (         base.GetType ( ) != typeof ( object ) );      if ( !base.Equals ( obj ) )     {         return false;     }      // STEP 6: Compare identifying fields for equality.     return ( ( this.X.Equals ( obj.X ) ) &amp;&amp; ( this.Y.Equals ( obj.Y ) ) ); }
81862
Does string immutability work by statement, or by strings within a statement?   For example, I understand that the following code will allocate two strings on the heap.  string s = "hello "; s += "world!";   "hello" will remain on the heap until garbage collected; and s now references "hello world!" on the heap. However, how many strings does the following line allocate on the heap...1 or 2? Also, is there a tool/way to verify the results?  string s = "goodbye " + "cruel world!";
46765
Take the below code:  private void anEvent(object sender, EventArgs e) {     //some code }     What is the difference between the following ?  [object].[event] += anEvent;  //and  [object].[event] += new EventHandler(anEvent);   [UPDATE]  Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
67060
I want to be able to have LinkedList.contains() return true for a custom comparator.  Suppose that I have 1 LinkedList and 2 objects  LinkedList&lt;MyObject&gt; myList = new LinkedList&lt;MyObject&gt;();  MyObject a = new MyObject("HELLO"); MyObject b = new MyObject("HELLO");   Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable)   ( a == b ) == true  however, when I do the following, myList does not return true for myList.contains(b)  myList.add(a) myList.contains(b) // == false   I think its because contains will check object reference and see that a and b are 2 distinct objects. Is there any way I can make it so I don't have to extend LinkedList to compare those objects?
3181
When writing custom classes it is often important to allow equivalence by means of the == and != operators. In Python, this is made possible by implementing the __eq__ and __ne__ special methods, respectively. The easiest way I've found to do this is the following method:  class Foo:     def __init__(self, item):         self.item = item      def __eq__(self, other):         if isinstance(other, self.__class__):             return self.__dict__ == other.__dict__         else:             return False      def __ne__(self, other):         return not self.__eq__(other)   Do you know of more elegant means of doing this? Do you know of any particular disadvantages to using the above method of comparing __dict__s?  Note: A bit of clarification--when __eq__ and __ne__ are undefined, you'll find this behavior:  &gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b False   That is, a == b evaluates to False because it really runs a is b, a test of identity (i.e., "Is a the same object as b?").  When __eq__ and __ne__ are defined, you'll find this behavior (which is the one we're after):  &gt;&gt;&gt; a = Foo(1) &gt;&gt;&gt; b = Foo(1) &gt;&gt;&gt; a is b False &gt;&gt;&gt; a == b True
40162
Please demonstrate how the ternary operator works with a regular if/else block. Example:  Boolean isValueBig = value &gt; 100 ? true : false;     Exact Duplicate: