Can I declare a HashMap instead of a HashMap?Differences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow can I create an executable JAR with dependencies using Maven?How to get an enum value from a string value in Java?Iterate through a HashMapHow do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?Java Hashmap: How to get key from value?How to update a value, given a key in a java hashmap?

Theorems that impeded progress

Why is consensus so controversial in Britain?

What does the "remote control" for a QF-4 look like?

What would happen to a modern skyscraper if it rains micro blackholes?

What are these boxed doors outside store fronts in New York?

Roll the carpet

Is it possible to run Internet Explorer on OS X El Capitan?

Does an object always see its latest internal state irrespective of thread?

Which country benefited the most from UN Security Council vetoes?

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

Are the number of citations and number of published articles the most important criteria for a tenure promotion?

Is it inappropriate for a student to attend their mentor's dissertation defense?

Was any UN Security Council vote triple-vetoed?

Are astronomers waiting to see something in an image from a gravitational lens that they've already seen in an adjacent image?

Horror movie about a virus at the prom; beginning and end are stylized as a cartoon

How much of data wrangling is a data scientist's job?

High voltage LED indicator 40-1000 VDC without additional power supply

How much RAM could one put in a typical 80386 setup?

Rock identification in KY

Is it possible for a square root function,f(x), to map to a finite number of integers for all x in domain of f?

LaTeX: Why are digits allowed in environments, but forbidden in commands?

Add text to same line using sed

Perform and show arithmetic with LuaLaTeX

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?



Can I declare a HashMap instead of a HashMap?


Differences between HashMap and Hashtable?Is Java “pass-by-reference” or “pass-by-value”?Sort a Map<Key, Value> by valuesHow can I create an executable JAR with dependencies using Maven?How to get an enum value from a string value in Java?Iterate through a HashMapHow do I determine whether an array contains a particular value in Java?How do I declare and initialize an array in Java?Java Hashmap: How to get key from value?How to update a value, given a key in a java hashmap?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I'm trying to insert keys into a hashmap but I don't really need values inserted. I could but they wouldn't be used. I know hashmaps can accept null keys and values but only one null key,value pair. I could map.put(key,null) with the values being null but that method seems inefficient. My intention is that I'm going to use the map.containsKey(key) method to determine if a key exists in a hashmap which is why I don't need a value.



With that being said, is there a way to declare HashMap<key> instead of HashMap<key,arbitraryValue> so I won't have to add unnecessary null values? Sorry if this may be a dumb question.










share|improve this question

















  • 9





    The data type that you're looking for is called a Set<E>.

    – Jacob G.
    Mar 8 at 2:00






  • 1





    Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

    – Jeremy
    Mar 8 at 2:00







  • 4





    The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

    – Ole V.V.
    Mar 8 at 2:07











  • I think Google might have an implementation of the HashSet that you might find interesting.

    – Adrian M.
    Mar 8 at 3:18

















0















I'm trying to insert keys into a hashmap but I don't really need values inserted. I could but they wouldn't be used. I know hashmaps can accept null keys and values but only one null key,value pair. I could map.put(key,null) with the values being null but that method seems inefficient. My intention is that I'm going to use the map.containsKey(key) method to determine if a key exists in a hashmap which is why I don't need a value.



With that being said, is there a way to declare HashMap<key> instead of HashMap<key,arbitraryValue> so I won't have to add unnecessary null values? Sorry if this may be a dumb question.










share|improve this question

















  • 9





    The data type that you're looking for is called a Set<E>.

    – Jacob G.
    Mar 8 at 2:00






  • 1





    Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

    – Jeremy
    Mar 8 at 2:00







  • 4





    The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

    – Ole V.V.
    Mar 8 at 2:07











  • I think Google might have an implementation of the HashSet that you might find interesting.

    – Adrian M.
    Mar 8 at 3:18













0












0








0


1






I'm trying to insert keys into a hashmap but I don't really need values inserted. I could but they wouldn't be used. I know hashmaps can accept null keys and values but only one null key,value pair. I could map.put(key,null) with the values being null but that method seems inefficient. My intention is that I'm going to use the map.containsKey(key) method to determine if a key exists in a hashmap which is why I don't need a value.



With that being said, is there a way to declare HashMap<key> instead of HashMap<key,arbitraryValue> so I won't have to add unnecessary null values? Sorry if this may be a dumb question.










share|improve this question














I'm trying to insert keys into a hashmap but I don't really need values inserted. I could but they wouldn't be used. I know hashmaps can accept null keys and values but only one null key,value pair. I could map.put(key,null) with the values being null but that method seems inefficient. My intention is that I'm going to use the map.containsKey(key) method to determine if a key exists in a hashmap which is why I don't need a value.



With that being said, is there a way to declare HashMap<key> instead of HashMap<key,arbitraryValue> so I won't have to add unnecessary null values? Sorry if this may be a dumb question.







java hashmap






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 8 at 1:58









AlexAlex

31




31







  • 9





    The data type that you're looking for is called a Set<E>.

    – Jacob G.
    Mar 8 at 2:00






  • 1





    Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

    – Jeremy
    Mar 8 at 2:00







  • 4





    The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

    – Ole V.V.
    Mar 8 at 2:07











  • I think Google might have an implementation of the HashSet that you might find interesting.

    – Adrian M.
    Mar 8 at 3:18












  • 9





    The data type that you're looking for is called a Set<E>.

    – Jacob G.
    Mar 8 at 2:00






  • 1





    Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

    – Jeremy
    Mar 8 at 2:00







  • 4





    The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

    – Ole V.V.
    Mar 8 at 2:07











  • I think Google might have an implementation of the HashSet that you might find interesting.

    – Adrian M.
    Mar 8 at 3:18







9




9





The data type that you're looking for is called a Set<E>.

– Jacob G.
Mar 8 at 2:00





The data type that you're looking for is called a Set<E>.

– Jacob G.
Mar 8 at 2:00




1




1





Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

– Jeremy
Mar 8 at 2:00






Why do you need a HashMap if you don't need key value pairs? Why not just use a list or a set?

– Jeremy
Mar 8 at 2:00





4




4





The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

– Ole V.V.
Mar 8 at 2:07





The HashSet class that you should be using, is implemented using HashMap, so apprently it’s not so inefficient as one might think. Don’t worry about it.

– Ole V.V.
Mar 8 at 2:07













I think Google might have an implementation of the HashSet that you might find interesting.

– Adrian M.
Mar 8 at 3:18





I think Google might have an implementation of the HashSet that you might find interesting.

– Adrian M.
Mar 8 at 3:18












1 Answer
1






active

oldest

votes


















0














As Jacob G. said, you should use a Set<E>.



A set is just a collection that does not contain any duplicates. The implementing class HashSet<E> actually uses a HashMap<K,V> under the hood, as mentioned by Ole V.V., but using a Set<E> in your code is the better approach IMO, because your problem does not require the values.



Additionally, there is a problem with using a HashMap<K,V> where all your values are null is in the get(K key) method. This method will return null if the requested key does not have an associated value. So how do you know if your call to get returned a valid or invalid null? i.e.



Map<Integer, Object> map = new HashMap<>();

// add entry 0 ->
map.put(0, null);

Object get1 = map.get(0); // returns null, so 0 must be a key in our map!
Object get2 = map.get(1); // also returns null, so is 1 a key too? No!


So, for your specific problem, I would try something like this!



Set<MyKey> set = new HashSet<>(); // or any implementing class

...

MyKey someKey = ...

// Check if your key set doesn't have some key, if so add it to the key set
if (!set.contains(someKey))
set.add(someKey);






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055678%2fcan-i-declare-a-hashmapkey-instead-of-a-hashmapkey-value%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    As Jacob G. said, you should use a Set<E>.



    A set is just a collection that does not contain any duplicates. The implementing class HashSet<E> actually uses a HashMap<K,V> under the hood, as mentioned by Ole V.V., but using a Set<E> in your code is the better approach IMO, because your problem does not require the values.



    Additionally, there is a problem with using a HashMap<K,V> where all your values are null is in the get(K key) method. This method will return null if the requested key does not have an associated value. So how do you know if your call to get returned a valid or invalid null? i.e.



    Map<Integer, Object> map = new HashMap<>();

    // add entry 0 ->
    map.put(0, null);

    Object get1 = map.get(0); // returns null, so 0 must be a key in our map!
    Object get2 = map.get(1); // also returns null, so is 1 a key too? No!


    So, for your specific problem, I would try something like this!



    Set<MyKey> set = new HashSet<>(); // or any implementing class

    ...

    MyKey someKey = ...

    // Check if your key set doesn't have some key, if so add it to the key set
    if (!set.contains(someKey))
    set.add(someKey);






    share|improve this answer



























      0














      As Jacob G. said, you should use a Set<E>.



      A set is just a collection that does not contain any duplicates. The implementing class HashSet<E> actually uses a HashMap<K,V> under the hood, as mentioned by Ole V.V., but using a Set<E> in your code is the better approach IMO, because your problem does not require the values.



      Additionally, there is a problem with using a HashMap<K,V> where all your values are null is in the get(K key) method. This method will return null if the requested key does not have an associated value. So how do you know if your call to get returned a valid or invalid null? i.e.



      Map<Integer, Object> map = new HashMap<>();

      // add entry 0 ->
      map.put(0, null);

      Object get1 = map.get(0); // returns null, so 0 must be a key in our map!
      Object get2 = map.get(1); // also returns null, so is 1 a key too? No!


      So, for your specific problem, I would try something like this!



      Set<MyKey> set = new HashSet<>(); // or any implementing class

      ...

      MyKey someKey = ...

      // Check if your key set doesn't have some key, if so add it to the key set
      if (!set.contains(someKey))
      set.add(someKey);






      share|improve this answer

























        0












        0








        0







        As Jacob G. said, you should use a Set<E>.



        A set is just a collection that does not contain any duplicates. The implementing class HashSet<E> actually uses a HashMap<K,V> under the hood, as mentioned by Ole V.V., but using a Set<E> in your code is the better approach IMO, because your problem does not require the values.



        Additionally, there is a problem with using a HashMap<K,V> where all your values are null is in the get(K key) method. This method will return null if the requested key does not have an associated value. So how do you know if your call to get returned a valid or invalid null? i.e.



        Map<Integer, Object> map = new HashMap<>();

        // add entry 0 ->
        map.put(0, null);

        Object get1 = map.get(0); // returns null, so 0 must be a key in our map!
        Object get2 = map.get(1); // also returns null, so is 1 a key too? No!


        So, for your specific problem, I would try something like this!



        Set<MyKey> set = new HashSet<>(); // or any implementing class

        ...

        MyKey someKey = ...

        // Check if your key set doesn't have some key, if so add it to the key set
        if (!set.contains(someKey))
        set.add(someKey);






        share|improve this answer













        As Jacob G. said, you should use a Set<E>.



        A set is just a collection that does not contain any duplicates. The implementing class HashSet<E> actually uses a HashMap<K,V> under the hood, as mentioned by Ole V.V., but using a Set<E> in your code is the better approach IMO, because your problem does not require the values.



        Additionally, there is a problem with using a HashMap<K,V> where all your values are null is in the get(K key) method. This method will return null if the requested key does not have an associated value. So how do you know if your call to get returned a valid or invalid null? i.e.



        Map<Integer, Object> map = new HashMap<>();

        // add entry 0 ->
        map.put(0, null);

        Object get1 = map.get(0); // returns null, so 0 must be a key in our map!
        Object get2 = map.get(1); // also returns null, so is 1 a key too? No!


        So, for your specific problem, I would try something like this!



        Set<MyKey> set = new HashSet<>(); // or any implementing class

        ...

        MyKey someKey = ...

        // Check if your key set doesn't have some key, if so add it to the key set
        if (!set.contains(someKey))
        set.add(someKey);







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 8 at 3:20









        Derek PlautzDerek Plautz

        5112




        5112





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55055678%2fcan-i-declare-a-hashmapkey-instead-of-a-hashmapkey-value%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

            Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

            Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved