How do I return an array of objects in java?

后端 未结 7 605
情书的邮戳
情书的邮戳 2021-01-03 05:15

How do I return an array of objects in java?

相关标签:
7条回答
  • 2021-01-03 05:57

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

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

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

    0 讨论(0)
  • 2021-01-03 06:02

    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]);
      }
    }
    
    0 讨论(0)
  • 2021-01-03 06:03
    public Object[] myMethod() {
      Object[] objectArray = new Object[3];
      return objectArray;
    }
    

    Simple enough, really.

    0 讨论(0)
  • 2021-01-03 06:04

    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 :

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

    Good luck;

    0 讨论(0)
  • 2021-01-03 06:06

    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)).
    0 讨论(0)
  • 2021-01-03 06:11

    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.

    0 讨论(0)
提交回复
热议问题