如何在java中返回一个对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2558290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:14:55  来源:igfitidea点击:

How do I return an array of objects in java?

java

提问by shil

How do I return an array of objects in java?

如何在java中返回一个对象数组?

回答by Yuval

public Object[] myMethod() {
  Object[] objectArray = new Object[3];
  return objectArray;
}

Simple enough, really.

很简单,真的。

回答by Jon Skeet

Well, you can only actually return an array of referencesto objects - no expressions in Java actually evaluate to objects themselves. Having said that, returning an array of Object references is easy:

好吧,您实际上只能返回对对象的引用数组- Java 中的表达式实际上不会对对象本身进行评估。话虽如此,返回一个对象引用数组很容易:

 public Object[] yourMethod()
 {
     Object[] array = new Object[10];
     // Fill array
     return array;
 }

(To be utterly pedantic about it, you're returning a referenceto an array of object references.)

(要彻底迂腐的话,你会返回一个参考给对象引用的数组。)

回答by Vaishak Suresh

Returning an object array has been explained above, but in most cases you don't need to. Simply pass your object array to the method, modify and it will reflect from the called place. There is no pass by value in java.

上面已经解释了返回一个对象数组,但在大多数情况下你不需要。只需将您的对象数组传递给方法,修改它就会从被调用的地方反射出来。java中没有传值。

回答by Venkat

Try the following example,

试试下面的例子,

public class array
{
  public static void main(String[] args)
  {
    Date[] a = new Date [i];

    a[0] = new Date(2, "January", 2005);
    a[1] = new Date(3, "February", 2005);
    a[2] = new Date(21, "March", 2005);
    a[3] = new Date(28, "April", 2005);

    for (int i = a.length - 1; i >= 0; i--) 
    {
      a.printDate();
    }
  }
}

class Date
{
  int day;
  String month;
  int year;

  Date(int d, String m, int y)
  {
    day = d;
    month = m;
    year = y;
  }

  public void printDate()
  {
    System.out.println(a[i]);
  }
}

回答by RubyDubee

Answers posted earlier solves your problem perfectly ... so just for sake of another choice .. i will suggest you to use List: may be ArrayList<Object>so it could go as :

之前发布的答案完美地解决了您的问题……所以只是为了另一种选择……我建议您使用List:可能是ArrayList<Object>这样,它可以作为:

public List<Object> getListOfObjects() {
   List<Object> arrayList = new ArrayList<Object>();
   // do some work
   return arrayList;
}

Good luck;

祝你好运;

回答by matsev

What is the data structure that you have?

你有什么数据结构?

  • If it is an array - just return it.
  • If it is a Collection- use toArray()(or preferably toArray(T[] a)).
  • 如果它是一个数组 - 只需返回它。
  • 如果它是一个集合- 使用toArray()(或最好toArray(T[] a))。

回答by Madushanka Sampath

try this

尝试这个

public ArrayList<ObjectsType> fName(){
   ArrayList<ObjectsType>objectsList=new ArrayList<>();
   objectList.add(objets);
   return objectList;
}