Web Log di Adrian Florea

"You know you've achieved perfection in design, not when you have nothing more to add, but when you have nothing more to take away." Antoine de Saint-Exupery
posts - 440, comments - 2715, trackbacks - 3944

My Links

Archives

Post Categories

Image Galleries

.RO Blogs

.RO People

.RO Sites

Blogs

Furls

Links

vinCitori

String ==-ity in Java e C#

L'articolo "(Not So) Stupid Questions: String Equality" su java.net, è nato dalle perplessità di Vladimir V. Ostromensky inviate alla redazione del sito, riguardanti il risultato "strano" del seguente codice Java:

Compile the following:

// StringTester.java
public class StringTester
{
  public static void main(String args[])   {
    String aString = "myValue";
    String bString = "myValue";
    String cString = "";

    if(args.length ==1 ) cString = args[0];

    boolean test1 = aString.equals(bString);
    System.out.println("a.equals(b): " + aString + ".equals("+bString+") is " + test1);

    boolean test2 = aString == bString;
    System.out.println("a==b: " + aString + " == " + bString+" is " + test2);

    boolean test3 = aString.equals(cString);
    System.out.println("a.equals(c): " + aString + ".equals("+cString+") is " + test3);

    boolean test4 = aString == cString;
    System.out.println("a==c: " + aString + " == " + cString+" is " + test4);
  }
}

When run with myValue as the command-line argument, this produces the following output:

a.equals(b): myValue.equals(myValue) is true
a==b: myValue == myValue is true
a.equals(c): myValue.equals(myValue) is true
a==c: myValue == myValue is false

Vediamo come si comporta lo stesso codice tradotto senza problemi in C#:

// StringTester.cs
using System;

class StringTester
{
  static void Main(String[] args)
  {
    string aString = "myValue";
    string bString = "myValue";
    string cString = "";

    if(args.Length ==1) cString = args[0];

    bool test1 = aString.Equals(bString);
    Console.WriteLine("a.Equals(b): {0}.Equals({1}) is {2}", aString, bString, test1);

    bool test2 = aString == bString;
    Console.WriteLine("a==b: {0} == {1} is {2}", aString, bString, test2);

    bool test3 = aString.Equals(cString);
    Console.WriteLine("a.Equals(c): {0}.Equals({1}) is {2}", aString, cString, test3);

    bool test4 = aString == cString;
    Console.WriteLine("a==c: {0} == {1} is {2}", aString, cString, test4);
  }
}

Il risultato è diverso (sempre passando myValue da linea di comando!):

a.Equals(b): myValue.Equals(myValue) is True
a==b: myValue == myValue is True
a.Equals(c): myValue.Equals(myValue) is True
a==c: myValue == myValue is True

cioè, esattamente quello che tanti programmatori Java si aspettavano di ottenere nel loro linguaggio :-)

Print | posted on sabato 12 giugno 2004 19:26 | Filed Under [ Carillon .NET ]

Powered by:
Powered By Subtext Powered By ASP.NET