4 ms·
Java, prints 1: Set<File> s = new HashSet<File>(); s.add( new File( "c:/temp" ) ); s.add( new File( "c:/temp" ) ); System.out.println( s.size
by thangalin 3y ago
Java, prints 1:
Set<File> s = new HashSet<File>();
s.add( new File( "c:/temp" ) );
s.add( new File( "c:/temp" ) );
System.out.println( s.size() );
C#, prints 2:
ISet<FileInfo> s = new HashSet<FileInfo>();
s.Add( new FileInfo( "c:/temp" ) );
s.Add( new FileInfo( "c:/temp" ) );
Console.WriteLine( s.Count );
C#, test fails:
string path = "/tmp/filename.txt";
FileInfo f = new FileInfo( path );
File.CreateText( path ).Dispose();
Assert.True( f.Exists );
f.Delete();
Assert.False( f.Exists );
https://en.wikipedia.org/wiki/Principle_of_least_astonishment https://en.wikipedia.org/wiki/Principle_of_least_astonishmen...
Languages have their strengths and weaknesses.
- metaltyphoon 3y agoFilInfo doesn’t override Equal operator in C#. HashSet will use it for comparison and those are two different object references so idk what the confusion is here.
- thangalin 3y agoA set is a collection of objects in which order has no significance, and multiplicity is generally also ignored. Observing the code alone, it isn't obvious that two FileInfo instances having the same path are themselves not equal. As has been mentioned elsewhere, FileInfo should not be hashable to prevent declaring it as a Set, avoiding the situation entirely. C# isn't flawless. Java isn't flawless.