Java map value returns null - java

I have kind of a really strange problem. I have a simple Map called vectors where I store StrategyPairs as keys and Vectors as the values. When I print it, I get this result:
{net.softwarepage.facharbeit.normalgame.logic.StrategyPair#131e56d7=(1.0;2.0), net.softwarepage.facharbeit.normalgame.logic.StrategyPair#1e1bc985=(2.0;2.0), net.softwarepage.facharbeit.normalgame.logic.StrategyPair#d5415975=(0.0;2.0), net.softwarepage.facharbeit.normalgame.logic.StrategyPair#5bf8c6e7=(2.0;1.0)}
As you can see StrategyPair#131e56d7 is mapped to a Vector (1,2).
Now I create a new StrategyPair. When I print it I get StrategyPair#131e56d7 (the same one as before).
However, if I now call vectors.get(strategyPair) it returns null.
This is somehow really strange as the key is the same (at least it prints the exact same thing out when I print it...)
The problem arises when I rename a strategy, e.g. I change the property name in the class "Strategy". Then suddenly the map which contains StrategyPairs (a wrapper class for two strategies) is messed up as I explained before...
EDIT:
When I print the HashMap I still get the same result as above, but the following code:
for(StrategyPair pair : vectors.keySet()) {
System.out.println(vectors.get(pair));
}
returns:
null
(2.0;2.0)
null
(2.0;1.0)

As #Rajendra Gujja mentioned in a comment, the "hashcode of your keys should not change after you keep them in the map". This is very true; once I changed all the hashcodes to simply use a UUID instead of the name property which changes, the problem is solved. Thanks for all of your answers!

Related

How to store null elements in some object array and to know they are stored intentionally(not generated by java)

I am creating ExpandableArray class what contains Product classes inside.
I have method add(Product p) that adds Product in first null position in my ExpandableArray.
And method replace(index int, Product p) - replaces product with this index by with p.
i have confronted following situation:
ExpandableArray expArr = new ExpandableArray(3); // let initial size be 3 products.
expArr.add(p1);
expArr.add(p2);
expArr.replace(0,null) // [null,p2,null].
notice that i replaced first element by null intentionally! method add shouldn't touch it, it should work with the second null.
But how do i do that?
My solution is to make integer[]intentionedNullIndexes array inside ExpandableArray, and it will contain all indexes will intentioned nulls. so method add firstly will check if this null index is in intentionedNullIndexes and if it is he won't touch it.
i don't like this solution because it's hard to implement and wastes MANY RAM. Any suggestions?
Your requirement is an XY-problem.
It's an antipattern when null has some kind of special meaning in your business logic. The only valid meaning of null - is no data (otherwise the code becomes muddy).
i don't like this solution because it's hard to implement and wastes MANY RAM
There's no need to waste lots of memory. You need only one reference to a placeholder object, which you can use as many times as you need.

how to get stored value from Preferences

i am trying to store something but i can't figure out how, i have searched and read a lot but i still have one problem.
problem is, if i use: if(myPreferences.getBoolean(k, true) == true) when i am trying to get my preferences with key "k" why i have to add there value true/false? how can i get stored value if i wrote into get method new one next to the old key?
i am trying to get the stored value, why add new one? i guess i don't get the concept? idk.
hope it's clear, thanks a lot for answers :-)
The second parameter on your getBoolean call is the default value if k doesn't exist yet (documentation reference).
Presumably, your software requires a preference to be set to some value, and you'll supply a reasonable default.
If you want to test if a preference exists at all, you can use something like nodeExists().

4 Key Value HashMap? Array? Best Approach?

I've got loads of the following to implement.
validateParameter(field_name, field_type, field_validationMessage, visibleBoolean);
Instead of having 50-60 of these in a row, is there some form of nested hashmap/4d array I can use to build it up and loop through them?
Whats the best approach for doing something like that?
Thanks!
EDIT: Was 4 items.
What you could do is create a new Class that holds three values. (The type, the boolean, and name, or the fourth value (you didn't list it)). Then, when creating the HashMap, all you have to do is call the method to get your three values. It may seem like more work, but all you would have to do is create a simple loop to go through all of the values you need. Since I don't know exactly what it is that you're trying to do, all I can do is provide an example of what I'm trying to do. Hope it applies to your problem.
Anyways, creating the Class to hold the three(or four) values you need.
For example,
Class Fields{
String field_name;
Integer field_type;
Boolean validationMessageVisible;
Fields(String name, Integer type, Boolean mv) {
// this.field_name = name;
this.field_type = type;
this.validationMessageVisible = mv;
}
Then put them in a HashMap somewhat like this:
HashMap map = new HashMap<String, Triple>();
map.put(LOCAL STRING FOR NAME OF FIELD, new Field(new Integer(YOUR INTEGER),new Boolean(YOUR BOOLEAN)));
NOTE: This is only going to work as long as these three or four values can all be stored together. For example if you need all of the values to be stored separately for whatever reason it may be, then this won't work. Only if they can be grouped together without it affecting the function of the program, that this will work.
This was a quick brainstorm. Not sure if it will work, but think along these lines and I believe it should work out for you.
You may have to make a few edits, but this should get you in the right direction
P.S. Sorry for it being so wordy, just tried to get as many details out as possible.
The other answer is close but you don't need a key in this case.
Just define a class to contain your three fields. Create a List or array of that class. Loop over the list or array calling the method for each combination.
The approach I'd use is to create a POJO (or some POJOs) to store the values as attributes and validate attribute by attribute.
Since many times you're going to have the same validation per attribute type (e.g. dates and numbers can be validated by range, strings can be validated to ensure they´re not null or empty, etc), you could just iterate on these attributes using reflection (or even better, using annotations).
If you need to validate on the POJO level, you can still reuse these attribute-level validators via composition, while you add more specific validations are you´re going up in the abstraction level (going up means basic attributes -> pojos -> pojos that contain other pojos -> etc).
Passing several basic types as parameters of the same method is not good because the parameters themselves don't tell much and you can easily exchange two parameters of the same type by accident in the method call.

Objectify: Get list of Strings NOT EQUAL to provided value

I need to get the list of items whose datePublished IS NOT "". However, the code below doesn't work. Any ideas? Thanks
Query<Diagram> q=ofy.query(Diagram.class).filter("datePublished !=", "").order("-likes").limit(18);
When applying an inequality filter in the GAE datastore there are some restrictions.
You can read more here: https://developers.google.com/appengine/docs/java/datastore/queries
In this case, to have an inequality on datePublished you must order on that same field primarily before you can order on another.
So assuming the datePublished field is indexed:
Query<Diagram> q=ofy.query(Diagram.class).filter("datePublished !=", "").order("datePublished").order("-likes").limit(18);
Assuming this isn't a migration concern, you may want to consider denormalising this data when you store it, for example setting a 'noDatePublished' boolean.

Newbie: Using a variable as the rhs argument to the dot operator? [duplicate]

This question already has answers here:
Dynamic variable names Java
(3 answers)
Closed 9 years ago.
I have a list of objects and I'll need to access a specific one based off of random user input corresponding to an id. My limited knowledge at this point led me to something like:
String id;
if(id.equals("apple")){ //fixed silly error, thanks
return objectList.id.memberName;
} //etc...
Is this possible, or is there a better approach?
Sounds like you want a HashMap.
It works like a telephone directory - you put in keys and values, and use the key to look up a value (much like you'd use someone's name to look up their number in a telephone directory.)
Your example also wouldn't work at all, because you're using = in the if statement, which is an assignment statement rather than an equality check. == is what you were probably trying to get, but in this case you shouldn't use that either - instead use .equals() which you should always use when strings are concerned.)
HashMap<String, SomeValueObject> myMap = new HashMap<String, SomeValueObject>();
myMap.put("apple", value);
String id;
if (id.equals("apple")) {
return myMap.get("apple");
}
Essentially you instantiate a HashMap that has two parts to it; a Key and a Value (respectively. When I do myMap.get("apple"), it searches for the KEY "apple". I did myMap.put("apple", value) which makes the Key "apple" be mapped to a certain value that you want.
Also you need to use id.equals("apple") because a String is an object, and if you tried id == "apple" (which I think you meant), it will not work because it will not compare the value of the String but rather the address of it.
#berry120 has provided a practical answer. In general, it sounds like you want to lookup values based on some key. Look at the Map interface and what the JDK offers for concrete implementations.
The value of a variable is only available at run time. On the other hand, a variable name must be known at compile time. So no, you cannot do this exactly the way you are asking. Using a Map will probably be the best solution to your problem.

Categories

Resources