Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java method returning object or directly manipulate it?

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

  • using hashmap as an example here, but other objects would behave the same
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...

like image 924
Linxy Avatar asked Feb 25 '16 19:02

Linxy


People also ask

Can a method return an object Java?

In java, a method can return any type of data, including objects.

What is meant by returning an object from a method Java?

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.

How do you return an object to an object in Java?

"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.

How do you manipulate an object in Java?

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);


2 Answers

Well, think about the case where the method manipulates an existing non-empty map. In that case the first example makes perfect sense.

like image 53
luksch Avatar answered Nov 05 '22 04:11

luksch


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."

like image 26
Ceelos Avatar answered Nov 05 '22 03:11

Ceelos