Using HashMap put() - arrays

I've been testing out HashMap recently and I've stumbled upon an interesting problem. I have an array, a3, that I have set some arbitrary values. I then take this array and put it into a HashMap instance map.
My problem is that when I assign an Object instance the value of put("a3", a3), I can't seem to print out the address of the instance.
For example:
HashMap<Object, Object> map = new HashMap<Object, Object>();
int[] a3 = new int[] {1, 2, 3, 4};
map.put("a3", a3);
When I call System.out.println(map.put("a3", a3), I'm given an address in memory.
However, if I create an object instance and then try to print out that instance I get null.
Object copy = map.put("a3", a3);
System.out.println(copy);
Running the above segment gives me a value of null.
Any reason why both these statements, which appear identical, give me different results?

Read the API Documentation for a HashMap. Null is returned if no value existed in the map that matches what you are inserting.
http://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html#put%28K,%20V%29
So if "a3" existed in the map already, the you would get a return, but since it doesn't then you get back null. "a3" has been put into the map but you didn't print the map, you printed the return from put().

As #James_Massey say, if you consult official documentation, you can see that the return value for put() method is:
the previous value associated with key, or null if there was no
mapping for key. (A null return can also indicate that the map
previously associated null with key.)

Related

Why is my object not changing when I reassign properties in a forEach loop?

I am fetching an array of objects from an RX/JS call from an http backend. It returns an object which I am then trying to work with. I am making changes to this object using a for loop (in this example I am trying the .forEach because I have tried a number of different things and none of them seem to work.
When I run the code, I get a very weird problem. If I return the values of the properties, I get the new values (i.e. correctionQueued returns as true, etc.) but in the very next line, when I return the object, those same values are the same as the original (correctionQueued === false, etc.) HOWEVER, correctionStatus (which does not exist on the original object from http) sets just fine.
I don't understand how
array[index].correctionQueued can return true, but
array[index] returns an object with correctionQueued as false.
After the loop, the original array (checklistCopy) is identical to the object before the forEach loop, except the new property (correctionStatus) is now set, but all properties that I changed that were part of the original object remain as they were.
I have tried using a for of, for in, and .forEach. I have used the index to alter the original array, always the same result. Preexisting properties do not change, new properties are added. I have even tried working on a copy of the object in case there is something special about the object returned from rxjs, but to no avail.
checklistCopy.forEach((checklistItem, index, array) => {
if (checklistItem.crCode.isirName === correctionSetItem) {
array[index].correctionQueued = true;
array[index].correctionValue = mostRecentCorrection.correctionValue;
array[index].correctionStatus = mostRecentCorrection.status;
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
console.log(array[index]);
}
}
);
I don't get an error, but I get..
Original object is:
correctionQueued: false;
correctionValue: JAAMES;
--
console.log(array[index].correctionQueued, array[index].correctionValue, array[index].correctionStatus);
true JAMES SENT
but when I print the whole object:
console.log(array[index]);
correctionQueued: false;
correctionValue: JAAMES;
correctionStatus: "SENT'; <-- This is set correctly but does not exist on original object.
console.log(array[index]) (at least in Chrome) just adds the object reference to the console. The values do not resolve until you expand it, so your console log statement is not actually capturing the values at that moment in time.
Change your console statement to: console.log(JSON.stringify(array[index])) and you should discover that the values are correct at the time the log statement runs.
The behavior you are seeing suggests that something is coming along later and changing the object properties back to the original value. Unless you show a more complete example, we can't help you find the culprit. But hopefully this answers the question about why your logs show what they show.
Your output doesn't make sense to me either but cleaning up your code may help you. Try this:
checklistCopy.forEach(checklistItem => {
checklistItem.correctionQueued = checklistItem.crCode.isirName === correctionSetItem;
if (checklistItem.correctionQueued) {
checklistItem.correctionValue = mostRecentCorrection.correctionValue;
checklistItem.correctionStatus = mostRecentCorrection.status;
console.log('checklistItem', checklistItem)
}
}
);

Storing values obtained from for each loop Scala

Scala beginner who is trying to store values obtains in a Scala foreach loop but failing miserably.
The basic foreach loop looks like this currently:
order.orderList.foreach((x: OrderRef) => {
val references = x.ref}))
When run this foreach loop will execute twice and return a reference each time. I'm trying to capture the reference value it returns on each run (so two references in either a list or array form so I can access these values later)
I'm really confused about how to go about doing this...
I attempted to retrieve and store the values as an array but when ran, the array list doesn't seem to hold any values.
This was my attempt:
val newArray = Array(order.orderList.foreach((x: OrderRef) => {
val references = x.ref
}))
println(newArray)
Any advice would be much appreciated. If there is a better way to achieve this, please share. Thanks
Use map instead of foreach
order.orderList.map((x: OrderRef) => {x.ref}))
Also val references = x.ref doesn't return anything. It create new local variable and assign value to it.
Agree with answer 1, and I believe the reason is below:
Return of 'foreach' or 'for' should be 'Unit', and 'map' is an with an changed type result like example below:
def map[B](f: (A) ⇒ B): Array[B]
Compare To for and foreach, the prototype should be like this
def foreach(f: (A) ⇒ Unit): Unit
So If you wanna to get an changed data which is maped from your source data, considering more about functions like map, flatMap, and these functions will traverse all datas like for and foreach(except with yield), but with return values.

Passing Ruby array elements to a method

I'm not a programmer, but I find myself writing some simple ruby and aren't sure about a few things.
I have the following function
def resolve_name(ns_name)
ip = Resolv.getaddress(ns_name)
return ip
end
and the array
array = ['ns-1.me.com', 'ns-2.me.com']
What I want to do is to pass every element in the array to the function to be evaluated, and spit out to... something. Probably a variable. Once I have the resolved IPs I'll be passing them to an erb template. Not quite sure yet how to handle when there may be 1 to 4 possible results either.
What I want think I need to do is do an each.do and typecast to string into my function, but I haven't been able to figure out how to actually do that or phrase my problem properly for google to tell me.
http://ruby-doc.org/core-2.0.0/doc/syntax/calling_methods_rdoc.html#label-Array+to+Arguments+Conversion Doesn't quite have what I'm looking for.
irb(main):010:0> resolved = resolve_name(array)
TypeError: no implicit conversion of Array into String
Any suggestions?
Take a look at the documentation for ruby's Enumerable, which arrays implement. What you're looking for is the map method, which takes each element of an enumerable (i.e. an array) and passes it to a block, returning a new array with the results of the blocks. Like this:
array.map{|element| resolve_name(element) }
As an aside, in your method, you do not need to use a local variable if all you're doing with it is returning its value; and the return statement is optional - ruby methods always return the result of the last executed statement. So your method could be shortened to this:
def resolve_name(ns_name)
Resolv.getaddress(ns_name)
end
and then you really all it's doing is wrapping a method call in another. So ultimately, you can just do this (with array renamed to ns_names to make it self-explanatory):
ns_names = ['ns-1.me.com', 'ns-2.me.com']
ip_addresses = ns_names.map{|name| Resolv.getaddress(name) }
Now ip_addresses is an array of IP addresses that you can use in your template.
If you pass an array you could do:
def resolve_name(ns_name)
res = []
ns_name.each do |n|
res << {name: n, ip: Resolv.getaddress(name) }
end
res
end
And get an array of hashes so you know which address has which ip

How to creata an array of JEditorPane

I want to create an array of JEditorPane depending on the size of a String array.
Is there a possibility to create an array of JEditorPane? If yes, how?
Here is an example:
String [] elements = {"0","1","2","3","4"};
JEditorPane ePane [] = new JEditorPane[5];
I want to to put each String element into the certain JEditPane, i.e
JEditorPane[0].setText(elements[0]);
etc. But I get a nullpointerexception when run I run.
Your problem is, that Java initializes a new array with the default value for the given type. In this case it is null, because the JEditorPane inherits from Object.
You cannot call a method on null - that is where the NullPointerException comes from.
The solution: make a loop in which you initialize the JEditorPane-objects in the array.
Then you can do JEditorPane[0].setText(elements[0]);

Mapping first 3 records in database to variables

I have a test spec where I use the following line of code to assign 3 variables to session tokens within my table:
#auth_token, #auth2_token, #auth3_token = Session.limit(3).map(&:token)
I now wish to assign 3 variables as a role classes from my Roles table which isn't restricted to one attribute only but the whole class. I have tried the following but it doesnt seem to be working:
#role1, #role2, #role3 = Role.limit(3).map
Can this be achieved? Any pointers would be greatly appreciated !!
It works for the auth tokens because map converts the relation object into an array which then gets assigned to the variables. For the roles just calling map returns an enumerable and not an array.
You can just call to_a directly on the relation object returned by the limit call in order to convert it to an array.
#role1, #role2, #role3 = Role.limit(3).to_a
Wasn't sure how to go about this but got round the problem using the following:
#role1 = Role.find_by_name!("First")
#role2 = Role.find_by_name!("Second")
#role3 = Role.find_by_name!("Third")

Resources