How to use a common C # dictionary, like a hashtable, used in Java?

I am following this tutorial and I am working with a Dictionary that I discovered is the equivalent of a Hashtable in Java.

I created my dictionary like this:

private Dictionary<String, Tile> tiles = new Dictionary<String, Tile>(); 

Although my dilemma is that when using the Dictionary, I cannot use get written in Java like this:

 Tile tile = tiles.get(x + ":" + y); 

How to do the same. What does it mean to get x: y as a result?

+6
source share
2 answers

Short answer

Use indexer or TryGetValue() . If there is no key, the first throws a KeyNotFoundException , and the last returns false.

There is really no direct equivalent to the Java Hashtable get() method. This is because Java get() returns null if the key is missing.

Returns the value to which the specified key is mapped, or null if this map does not contain a mapping for the key.

On the other hand, in C # we can map the key to a null value. If the pointer or TryGetValue() says that the value associated with the key is null, this does not mean that the key is not displayed. It just means that the key maps to zero.

Execution Example :

 using System; using System.Collections.Generic; public class Program { private static Dictionary<String, Tile> tiles = new Dictionary<String, Tile>(); public static void Main() { // add two items to the dictionary tiles.Add("x", new Tile { Name = "y" }); tiles.Add("x:null", null); // indexer access var value1 = tiles["x"]; Console.WriteLine(value1.Name); // TryGetValue access Tile value2; tiles.TryGetValue("x", out value2); Console.WriteLine(value2.Name); // indexer access of a null value var value3 = tiles["x:null"]; Console.WriteLine(value3 == null); // TryGetValue access with a null value Tile value4; tiles.TryGetValue("x:null", out value4); Console.WriteLine(value4 == null); // indexer access with the key not present try { var n1 = tiles["nope"]; } catch(KeyNotFoundException e) { Console.WriteLine(e.Message); } // TryGetValue access with the key not present Tile n2; var result = tiles.TryGetValue("nope", out n2); Console.WriteLine(result); Console.WriteLine(n2 == null); } public class Tile { public string Name { get; set; } } } 
+9
source

The best way to get the value is

  bool Dictionary<Key, Value>.TryGetValue(Key key, out Value value); 

It will return a boolean value to determine if key present, and value correctly referenced or not.

This method is fast, since you only exit value when the key is displayed, so multiple hashing and dictionary searches are avoided.

So your code will be:

 private Dictionary<String, Tile> tiles = new Dictionary<String, Tile>(); Tile outValue; if(tiles.TryGetValue( x + ":" + y, out outValue)) { Console.WriteLine("I have this: " + outValue.ToString()); } else { Console.WriteLine("I have nothing"); } 

See MSDN .

+2
source

Source: https://habr.com/ru/post/987228/


All Articles