I have come upon this (to me weird) piece of code. I have actually never seen this used and never used it myself, so it was something quite confusing... which goes along the lines of
public static void fillData(HashMap<Object, Object> dataMap){
dataMap.put("key","value");
}
Now this was very confusing, as the way I learned you do it is more like this
public static HashMap<Object, Object> fillData(){
HashMap<Object, Object> dataMap = new HashMap<>();
dataMap.put("key","value");
return dataMap;
}
Now is there a time when I should use one way or the other? Im still pretty new to programming, but I havent found much of anything about this type of structure.
I also have experimented around and found this only works with objects, and not primitives...
In java, a method can return any type of data, including objects.
In Java, a method can return any type of data, including class types that you can create. For example, in the following Java program, the method incrByTen() returns an object in which the value of a is ten greater than it is in the invoking object.
"In order to return an object from a Java method, you must first declare a variable to hold a reference to the object." So in this case, Ball is a variable that is a reference to the object. Correct? redBall is a reference to the object created by the new Ball("red") statement.
Class reference is necessary when we want invoke a native static method declared in a Java class. We may create jclass and jobject as follows in C/C++ code. jclass jcls=env->FindClass("java/lang/String"); jobject jobj=env->AllocateObject(jcls);
Well, think about the case where the method manipulates an existing non-empty map. In that case the first example makes perfect sense.
I was googling this same subject in the morning and came across this discussion, which states that the first form of
public static void fillData(HashMap<Object, Object> dataMap){
dataMap.put("key","value");
}
is considered "a bad practice, vestigial or pre-OOP times."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With