0

My question resembles a lot the battle between "is java pass-by-value or pass-by-reference". But I still can't understand what happens when I pass an object in a function. For example let's say that I have a huge HashMap and I want it to be accessible by every object and every class. So I pass it as an argument to all functions that need it. To be more specific, I create this HashMap in the main function and then I have some objects that require it.

main()
{
    HashMap<Integer,Set<Integer> dataset=readDatasetfromFile(file);
    ArrayList<Object> objects=new ArrayList();

    //assume that I create and fill the list with objects

    for(int i=0;i<objects.size();i++)
    {
        int variable=objects.get(i).doSomething(dataset);
    }

}

But I don't understand if it copies it or not. There is no point in copying it every time I call a function, because that is a waste of time. It would be nice if it just passes the object as a reference. Thank you.

As I said none of the answered posts explicitly says if the whole object is copied bit by bit to the function or no, and that is my main question. So I don't see any resemblance to other questions.

jojoba
  • 544
  • 9
  • 19
  • 1
    Yes `it just passes the object as a reference` – Subir Kumar Sao Mar 31 '15 at 19:20
  • http://www.javacoffeebreak.com/faq/faq0066.html – duxfox-- Mar 31 '15 at 19:22
  • A simple experiment will confirm that. Padd the object to a funtion. Let that function modify one of the members. Pass that same object to another function and print the members. See if they have changed on the original "copy" – Tarik Mar 31 '15 at 19:23
  • 1
    [Java is Pass-by-Value, Dammit!](http://javadude.com/articles/passbyvalue.htm) – *I'm really tired of hearing folks (incorrectly) state "primitives are passed by value, objects are passed by reference". The terms "pass-by-value" semantics and "pass-by-reference" semantics have very precise definitions, and they're often horribly abused when folks talk about Java. I want to correct that...* – John Kugelman Mar 31 '15 at 19:25
  • So if the HashMap is for example 200 MegaBytes, then every time I pass it to a function, 200 MegaBytes are copied? Or it passes only the address of the object? – jojoba Mar 31 '15 at 19:31
  • 2
    The reference to the HashMap is passed by value (reassigning the parameter does not affect the caller). The HashMap itself is not copied. – Brett Kail Mar 31 '15 at 19:35

0 Answers0