C # Java HashMap equivalente


Viniendo de un mundo Java a uno de C# ¿hay un equivalente de HashMap? Si no, ¿qué recomendarías?

Author: Thorarin, 2009-08-13

7 answers

Dictionary es probablemente el más cercano. System.Collections.Generic.Dictionary implementa el System.Collections.Generic.IDictionary interfaz (que es similar a la interfaz Map de Java).

Algunas diferencias notables que debe tener en cuenta:

  • Agregar / Obtener elementos
    • El HashMap de Java tiene los métodos put y get para establecer / obtener elementos
      • myMap.put(key, value)
      • MyObject value = myMap.get(key)
    • El diccionario de C # usa [] indexación para establecer / obtener elemento
      • myDictionary[key] = value
      • MyObject value = myDictionary[key]
  • null claves
    • Java HashMap permite claves nulas
    • . NET Dictionary lanza un ArgumentNullException si intenta agregar una clave nula
  • Añadiendo una clave duplicada
    • El HashMap de Java reemplazará el valor existente con el nuevo.
    • Dictionary de.NET reemplazará el valor existente con el nuevo si utiliza [] indexación. Si utiliza el método Add, en su lugar lanzará un ArgumentException.
  • Intentando obtener una clave inexistente
    • El HashMap de Java devolverá null.
    • . NET Dictionary lanzará un KeyNotFoundException. Puede utilizar el TryGetValue método en lugar de la indexación [] para evitar esto:
      MyObject value = null; if (!myDictionary.TryGetValue(key, value)) { /* key doesn't exist */ }

Dictionary's tiene a ContainsKey método que puede ayudar a lidiar con los dos problemas anteriores.

 378
Author: Powerlord,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 02:22:10

De C# equivalente a Java HashMap

Necesitaba un Diccionario que aceptara una clave "null", pero parece que no hay una nativa, así que he escrito la mía. Es muy simple, en realidad. Heredé del Diccionario, agregué un campo privado para mantener el valor de la clave" null", luego sobrescribí el indexador. Dice así:

public class NullableDictionnary : Dictionary<string, string>
{
    string null_value;

    public StringDictionary this[string key]
    {
        get
        {
            if (key == null) 
            {
                return null_value;
            }
            return base[key];
        }
        set
        {
            if (key == null)
            {
                null_value = value;
            }
            else 
            {
                base[key] = value;
            }
        }
    }
}

Espero que esto ayude a alguien en el futuro.

==========

Lo modifiqué a este formato

public class NullableDictionnary : Dictionary<string, object>
 35
Author: KeithC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-12 21:17:41

Déjame ayudarte a entenderlo con un ejemplo de "algoritmo de codaddict"

'Diccionario en C# es 'Hashmap en Java " en el universo paralelo.

Algunas implementaciones son diferentes. Vea el ejemplo a continuación para entender mejor.

Declarando Java HashMap:

Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

Declarando el Diccionario C#:

Dictionary<int, int> Pairs = new Dictionary<int, int>();

Obtener un valor de una ubicación:

pairs.get(input[i]); // in Java
Pairs[input[i]];     // in C#

Establecer un valor en la ubicación:

pairs.put(k - input[i], input[i]); // in Java
Pairs[k - input[i]] = input[i];    // in C#

An General Ejemplo se puede observar desde abajo algoritmo de Codaddict.

El algoritmo de Codaddict en Java:

import java.util.HashMap;

public class ArrayPairSum {

    public static void printSumPairs(int[] input, int k)
    {
        Map<Integer, Integer> pairs = new HashMap<Integer, Integer>();

        for (int i = 0; i < input.length; i++)
        {
            if (pairs.containsKey(input[i]))
                System.out.println(input[i] + ", " + pairs.get(input[i]));
            else
                pairs.put(k - input[i], input[i]);
        }

    }

    public static void main(String[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        printSumPairs(a, 10);

    }
}

El algoritmo de Codaddict en C #

using System;
using System.Collections.Generic;

class Program
{
    static void checkPairs(int[] input, int k)
    {
        Dictionary<int, int> Pairs = new Dictionary<int, int>();

        for (int i = 0; i < input.Length; i++)
        {
            if (Pairs.ContainsKey(input[i]))
            {
                Console.WriteLine(input[i] + ", " + Pairs[input[i]]);
            }
            else
            {
                Pairs[k - input[i]] = input[i];
            }
        }
    }
    static void Main(string[] args)
    {
        int[] a = { 2, 45, 7, 3, 5, 1, 8, 9 };
        //method : codaddict's algorithm : O(n)
        checkPairs(a, 10);
        Console.Read();
    }
}
 7
Author: Ajay Yadiki,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-12 15:07:29

Consulte la documentación de MSDN para la clase Hashtable.

Representa una colección de pares clave y valor que se organizan en función del código hash de la clave.

También, tenga en cuenta que esto no es seguro para el hilo.

 5
Author: Ray,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-11 15:35:50

Use Dictionary - usa hashtable pero es typesafe.

También, su código Java para

int a = map.get(key);
//continue with your logic

Se codificará mejor en C # de esta manera:

int a;
if(dict.TryGetValue(key, out a)){
//continue with your logic
}

De esta manera, puede abarcar la necesidad de la variable "a" dentro de un bloque y todavía es accesible fuera del bloque si la necesita más tarde.

 2
Author: Shree Harsha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-09 01:49:55

La respuesta es

Diccionario

Echa un vistazo a mi función, su simple add utiliza las funciones miembro más importantes dentro del Diccionario

Esta función devuelve false si la lista contiene elementos Duplicados

 public static bool HasDuplicates<T>(IList<T> items)
    {
        Dictionary<T, bool> mp = new Dictionary<T, bool>();
        for (int i = 0; i < items.Count; i++)
        {
            if (mp.ContainsKey(items[i]))
            {
                return true; // has duplicates
            }
            mp.Add(items[i], true);
        }
        return false; // no duplicates
    }
 0
Author: Basheer AL-MOMANI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-21 17:16:48

Solo quería dar mis dos centavos.
Esto es de acuerdo con la respuesta de @Powerlord.

Pone "null" en lugar de null cadenas.

private static Dictionary<string, string> map = new Dictionary<string, string>();

public static void put(string key, string value)
{
    if (value == null) value = "null";
    map[key] = value;
}

public static string get(string key, string defaultValue)
{
    try
    {
        return map[key];
    }
    catch (KeyNotFoundException e)
    {
        return defaultValue;
    }
}

public static string get(string key)
{
    return get(key, "null");
}
 0
Author: ossobuko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-14 08:51:19