简体   繁体   English

如何在Java中将对象的引用作为参数返回

[英]How to return reference to object as parameter in Java

Although I've programmed C, C++ and C# for many years I'm am only superficially familiar with Java. 虽然我已经编写了C,C ++和C#多年,但我只是表面上熟悉Java。 Helping my Comp Sci son with a Java college project he had a need to return references to two objects from a method in Java. 通过Java学院项目帮助我的Comp Sci子,他需要从Java中的方法返回对两个对象的引用。 I suggested returning one as the function value and the 2nd as a reference. 我建议将一个作为函数值返回,将第二个作为参考。 He wasn't sure how to do this. 他不知道该怎么做。 I did a little research and realized it may not be possible. 我做了一点研究,意识到这可能是不可能的。 My question is in Java what is the common method used when a method needs to return more than one reference to an object. 我的问题是在Java中,当一个方法需要返回一个对象的多个引用时,常用的方法是什么。 Here's the specific example in my sons case. 这是我儿子案例中的具体例子。

// This method returns references to the head and tail objects from the passed in 
// linked list.  The head object is returned as the function value and the tail is 
// returned as a parameter.
public Static Node GetHeadTail(List list, Node tail)

I realize the above doesn't work in Java since the tail is a reference to node and in Java the reference itself is passed by value. 我意识到上面的代码在Java中不起作用,因为tail是对节点的引用,而在Java中引用本身是通过值传递的。 What is the most common way of dealing with this in Java? 在Java中处理这个问题最常见的方法是什么? My son's solution was to return an array of 2 Node objects for the function value. 我儿子的解决方案是为函数值返回一个2节点对象的数组。 I said that was a poor solution because it doesn't document the meaning of each element of the array. 我说这是一个糟糕的解决方案,因为它没有记录数组中每个元素的含义。 Another solution would be to create an object that contained the head and tail references. 另一种解决方案是创建一个包含头部和尾部引用的对象。 However in the particular example it was the head pointer that was of most interest and if an object was returned it would create undesired coding overhead for the caller of the method if all they wanted was the head. 然而,在特定示例中,头指针是最感兴趣的,并且如果返回对象,则如果他们想要的只是头部,则会为该方法的调用者创建不期望的编码开销。

In this case, java programmers would commonly create a class with 2 members: head and tail . 在这种情况下,java程序员通常会创建一个包含2个成员的类: headtail That would be the return type for the getHeadTail(List list) method. 这将是getHeadTail(List list)方法的返回类型。

You can only pass by value in Java. 您只能通过Java传递值。 Your best solution is the second one your son suggested, ie return an object that has the head and tail. 你最好的解决方案是你儿子建议的第二个解决方案,即返回一个有头部和尾部的物体。

Java is always pass-by-value. Java始终是按值传递的。 The difficult thing can be to understand that Java passes objects as references and those references are passed by value. 困难的是可以理解Java将对象作为引用传递,并且这些引用是按值传递的。 ( Is Java "pass-by-reference" or "pass-by-value"? ) Java是“通过引用传递”还是“按值传递”?

However, you are capable of doing something like this: 但是,你有能力做这样的事情:

public static void main(String[] args)
{
    Car c = new Car("Blue");
    System.out.println(c.getName());
    changer(c);
    System.out.println(c.getName());
}

public static void changer(Car c)
{
    c.setName("Red");
}

The Car class. 汽车课。

public class Car 
{
    private String name;

    public Car(String n)
    {
        name = n;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String n)
    {
        name = n;
    }
}

The output will be: 输出将是:

Blue
Red

Knowing this, you will be able to change what tail points to and still be able to return the head . 知道了这一点,你就可以改变tail指向的东西,并且仍然能够返回head

Java does this interesting thing that's sort of a hybrid between pass-by-value and pass-by-reference. Java做了这个有趣的事情,它是传递值和传递引用之间的混合体。 Basically, a parameter cannot be changed by the function, but the function can ask the parameter to change itself via calling some method within it. 基本上,函数不能更改参数,但函数可以通过调用其中的某个方法来请求参数更改自身。 This answer does a pretty good job of explaining it. 这个答案很好地解释了它。

In response to "What is the most common way of dealing with this in Java?" 回应“在Java中处理这个问题的最常见方式是什么?” your solution of creating a class that contains a head and tail reference is probably the most common and best practice. 你创建一个包含头尾参考的类的解决方案可能是最常见和最好的做法。 If possible, it may even be best to just have separate getHead and getTail methods. 如果可能的话,最好只有单独的getHead和getTail方法。

One slightly less obvious solution: Use one of the built-in types, like Queue or LinkedList, which already has a head and tail. 一个稍微不那么明显的解决方案:使用其中一个内置类型,如Queue或LinkedList,它们已经有头尾。

LinkedList list = new LinkedList();
head = list.getFirst();
tail = list.getLast();

There's a bunch of types like this one depending on your need. 根据您的需要,有很多这样的类型。 Read the docs. 阅读文档。

A somewhat hacky technique is to use a an array as a parameter. 一种有点hacky技术是使用数组作为参数。 Then, the function can change the value of one or more element to "return" it. 然后,该函数可以更改一个或多个元素的值以“返回”它。 It's not pretty but gets the job done and avoids the need to create special wrapper objects for this purpose. 它并不漂亮,但可以完成工作,并且无需为此目的创建特殊的包装器对象。

Just as a side note, Scala solves this issue by letting you return tuples. 正如旁注,Scala通过让你返回元组来解决这个问题。

If you are trying to implement a method that return multiple values as arguments, you can use something like this: 如果您尝试实现一个返回多个值作为参数的方法,您可以使用以下内容:

public class Future<T> {
  private T instance;

  public T get() {
    return this.instance;
  }

  public void set(T value) {
    this.instance = value;
  }
}

And use it like this: 并像这样使用它:

class MyCrazyClass {

  private static void myCrazyMethod(Future<String> returnVal1, Future<Integer> returnVal2, Future<Float> returnVal3) {
    returnVal1.set("We are cool!");
    returnVal2.set(123);
    returnVal3.set(321F);
  }

  public static void main(String[] args) {
    Future<String> strRetVal = new Future<>();
    Future<Integer> intRetVal = new Future<>();
    Future<Float> floatRetVal = new Future<>();

    myCrazyMethod(strRetVal, intRetVal, floatRetVal);

    System.out.println(strRetVal.get());
    System.out.println(intRetVal.get());
    System.out.println(floatRetVal.get());
  }
}

Output: 输出:

We are cool!
123
321.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 mongodb Java驱动程序。 如何通过引用返回对象 - mongodb java driver. How to return object by reference Java如何返回具有依赖于指定参数的类的对象? - How can Java return an object with class dependent on a specified parameter? Java:在参数的指针中传递对象(按引用传递) - Java: pass object in pointer in parameter(pass by reference) Java构造函数是否返回Object引用? - Does a Java constructor return the Object reference? Java方法参数和返回类对象 - Java method parameter and return class object 在Java中,如何返回对对象的引用,以便可以使用赋值运算符修改对象 - In Java, how do you return reference to an object, so the object can be modified using assignment operator JAva:如何将自定义对象类型作为参数传递给方法,并返回相同的自定义对象类型值 - JAva:How to pass a custom object type as a parameter to a method and return the same custom object type value back 如何在Java中将table%rowtype的oracle pl / sql out参数引用为对象 - how to reference an oracle pl/sql out parameter of table%rowtype as an object in java 如何在Java字节码中引用“ this”对象 - How to reference “this” object in java bytecode 如何在Java中引用另一个对象? - How to reference to another object in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM