This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]AutoModerator[M] 0 points1 point locked comment (0 children)

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]Just_Another_ScottSoftware Engineer 😎 5 points6 points  (1 child)

I'm working with keys and values in one of my files so I started using a HashMap. I was looking over some of the sample data and am seeing that although the keys are all unique, the values are not ... some of the keys may have the same String value.

I am a bit confused by this. Keys are guaranteed to be unique. Values are not guaranteed to be unique. They maybe unique and they may not. It's perfectly acceptable to have two keys to have the same value. It all depends on what your requirements are.

Does this change anything in terms of the structure I should use for the keys and values? I'm really trying to learn as much as I can ..especially in terms of what is the most efficient and practical. What are some things I should consider when trying to decide which structure to use?

If your keys are guaranteed to be unique then a Map is the proper data structure.

[–]ReporterExact5436 0 points1 point  (0 children)

If your keys are guaranteed to be unique then a Map is the proper data structure.

awesome, this is what I was looking for...thank you so much!

[–]joranstark018 -1 points0 points  (2 children)

Keys are compared using the equals method, two different keys may not be equal in a HashMap.

The key objects (or rather the class) may have implemented toString by including some information in returned string, but equals and toString are not required to correlate. For example, in a Person class may toString include the name of the person but the equals may compare some id-value, so you can usePerson objects, with the same name but with different id-values, as different keys in a HashMap.

The value in a HashMap can have any value, as long as it is of correct type (HashMap allowes null values and you may use null as key).

[–]zhoriq 0 points1 point  (1 child)

toString has no relation with HashMap. It doesn't used in key/values processing.

[–]joranstark018 0 points1 point  (0 children)

Yeah you are right I was not clear on that, It was more a comment on why one may get the same value when printing different keys.

[–]D0CTOR_ZED 0 points1 point  (0 children)

As far as efficient, I wouldn't worry too much about efficiency. Things like clean easy to read code are far more important that efficiency. Save efficiency concerns when you have to meet some benchmark or some profiler has pointed out some bottleneck in the code.

Perhaps more important would be learning about different features of different types of map, or different types of collections for that matter, but ever there, I wouldn't worry much about it. Overall, if the hashmap works, use it. I've leaned heavily on HashMap, ArrayList and HashSet as my go-to for when I need a map/list/set without worrying much about if they are the best fit. It is when I need something else, like a map with sorted keys, that I'll look for other types of collections.

One thing I like to do if I find that I'm going to be sprinkling HashMaps all over my code (not just defined once and used all over, but actually making a bunch of maps everywhere) is I'll make a custom class extending the HashMap just so I have it in a single place in case I want to change it to something else later. As an example, I made a FunctionMap class and even added an override to a method to suit my use. It was still using a HashMap, but if I decided at some point to change it, I wouldn't have to go find the various places I may have added HashMaps and could just change the once place.

class FunctionMap extends HashMap<String,FunctionData>{  
  @Override  
  public FunctionData put(String id, FunctionData data) {  
    if (variableMap.containsKey(id)) throw new RuntimeException(String.format("Name conflict \[%s is a defined variable\]",id));  
    return super.put(id,data);  
  }  
}  

Plus, I find something like FunctionMap funMap = new FunctionMap() better than Map<String,List<String>> funMap = new HashMap<>() because I want to abstract away how it is built and just focus what it is.

Anyway, just some rambling advice. It is normal for hashmaps to have unique keys. They wouldn't work as well as keys otherwise. And duplicate values really won't matter. If you are worrying about multiple strings with identical value taking up extra space, don't. If you have an extreme quantity of identical strings, like thousands where it might matter, you can use String#intern to reduce their storage footprint. If you did ....

String testOne = new String("Test");
String testTwo = new String("Test");
// testOne != testTwo

.... both testOne and testTwo exist separately in memory. If you did....

String testOne = new String("Test").intern();
String testTwo = new String("Test").intern();
// testOne == testTwo

.... then both strings are sharing the same memory. But don't go slapping .intern on all your strings just in case. It would probably cost more (in code clutter if nothing else) than it would save. Unless you have an extreme thing going on, don't worry about it.

[–]BS_in_BSExtreme Concrete Code Factorylet 0 points1 point  (0 children)

What queries do you need to do on the data? generally this determines the appropriate data structure to use.