JAVA Return an object or pass by reference

This is a question for beginners.

Is there a difference in JAVA between passing an object as an argument to a method or returning this object from a method. For example: is it better to pass a list as an argument and populate it in a method, or just allow a method to return a list?

My guess is that this should not be any difference, as the link is returned and nothing is copied. But is there something more subtle?

early

Altober

+4
source share
5 answers

Firstly, in Java there is no "pass by reference": the language passes links by value (this is not the same thing).

: " ": , .

: , . , .

interface DataSource {
    void supplyData(List<Data> list);
}

:

interface DataSource {
    List<Data> supplyData(); 
}

, :

List<Data> bigList = new ArrayList<Data>();
foreach (DataSource s : mySources) {
    s.supplyData(bigList);
}

supplyData , :

List<Data> bigList = new ArrayList<Data>();
foreach (DataSource s : mySources) {
    List<Data> tmp = s.supplyData();
    bigList.addAll(tmp);
}

tmp, .

, - , .

, , . DataSource , , , , , ..

+4

, , , .

,

public void myMethod(List list) {
    list.add(new Object());
}

public List myMethod() {
    List list = new ArrayList();
    list.add(new Object());
    return list;
}

, .

, . , . , .

, . , , , , null. .

+4

dasblinkenlight, ( ), .

, , , . , .

, :

  • return Collections.emptyList(),
  • ArrayList
  • subList , ,
  • - , , , , , .
+2

, . , . , (, ).

.

+1

, , , Java .

- JAVA ? , , .

? , . ?

My guess is that this should not be any difference as the link is returned and nothing is copied? Strictly speaking, this is not how the copy of the link is returned .

+1
source

All Articles