代码之家  ›  专栏  ›  技术社区  ›  Gustavo Puma

在方法内实例化两个对象以用作“返回值”

  •  2
  • Gustavo Puma  · 技术社区  · 14 年前

    我有以下课程:

    public class Matriz
    {
      ...
      static public void create(Matriz a, Matriz b)
      {
         ...
         a=new Matriz(someValue,anotherValue);
         b=new Matriz(someValue,anotherValue);    
         ...
      }
    }
    

    在我的主要方法中:

    public static void main(String[] args)
    {
      Matriz a=null,b=null;
      Matriz.create(a,b);
      //these are null
      a.print();
      b.print();
    }
    

    方法create()的作用是“返回”两个matriz对象。我怎么能这样做?

    6 回复  |  直到 14 年前
        1
  •  2
  •   Grodriguez    14 年前

    最简单的方法是返回一个数组:

    static public Matriz[] create()
    {
        ...
        Matriz[] m = new Matriz[2];
        m[0] = new Matriz(someValue, anotherValue);
        m[1] = new Matriz(someValue, anotherValue); 
        ...
        return m;
    }
    
        2
  •  3
  •   Chris Knight    14 年前

    以下是一些建议:

    1)返回它们的列表:

    public List<Matriz> create(..);
    ...
    List<Matriz> matrizList = Matriz.create(...);
    a = matrizList.get(0);
    b = matrizList.get(1);
    

    2)返回方法对象

    public MatrizHolder create(...);
    ...
    MatrizHolder holder = Matriz.create(...);
    a = holder.getA();
    b = holder.getB();
    

    3)一次创建一个

    public Matriz create(...);
    ...
    a = Matriz.create(..);
    b = Matriz.create(..);
    

    作为旁白,不能将空引用传递给方法,不能在方法中对其进行初始化,也不能在方法完成时保留引用。因此,将a和b传递给上面代码中的create方法是没有意义的。

        3
  •  2
  •   Bozho    14 年前

    或者返回两个值的数组:

    public static Matriz[] create(..) {
    
       ...
       return new Matriz[] {a, b};
    }
    

    或者介绍一个新班级-

    class MatrizPair {
       private Matriz a;
       private Matriz b;
    
       // setter and getter for each
    }
    

    重要的是要注意,您的示例不起作用,因为Java是“按值传递”,而不是“通过引用”(读取)。 this )

        4
  •  1
  •   Sean Patrick Floyd    14 年前

    这种事情在Java中是行不通的,因为Java是按值调用,而不是通过引用来调用。

    如果您希望此功能,可以将任何类型的容器传递给方法(数组、 Collection ,一个 AtomicReference 等等,但是你不能只用一个变量。变量在传递到方法时被复制,因此该方法不能更改原始值。如果传递了一个容器,则可以从该方法中插入一个值,并且从原始上下文中可以看到该值,因为外部方法指向同一个容器对象(复制了引用,但没有复制值)。

        5
  •  1
  •   Codemwnci    14 年前

    首先,不应该传入要实例化的对象。只需返回一个数组。

    所以你的代码应该是这样的

    public class Matriz
    {
      ...
      static public Matriz[] create()
      {
         ...
         a=new Matriz(someValue,anotherValue);
         b=new Matriz(someValue,anotherValue);    
         ...
         return new  Matriz[] {a, b};
      }
    }
    

    你的主要方法是:

    public static void main(String[] args)
    {
      Matriz[] array = Matriz.create();
      array[0].print();
      array[1].print();
    }
    
        6
  •  0
  •   Andriy Sholokh    14 年前

    不能返回两个对象。只能返回对象的数组或集合。 在您的例子中,您可以将变量作为类字段,并在“create”方法中为它们分配一些内容。