Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it Possible to Return Two ArrayList values in One method in java?

Is there any way to return two values from one method....

Example:

public Class Sample
{
  public List<Date> returnTwoArrayList()
   {
      List<Date> startDate=new ArrayList<Date>();
      
      List<Date> endDate=new ArrayList<Date>();

     //So I want to Return Two values startDate and endDate ...It is Possible????
   }
}

i'm calling this method into My Service class and in that Storing StartDate and endDate into Database here these are Two different Columns

**StartDate      endDate**
2012-12-01     2012-12-05
2012-12-01     2012-12-15
2012-12-02     2012-12-10
2012-12-20     2012-12-25
2012-12-25     2012-12-31
 
like image 293
Java Developer Avatar asked Nov 28 '22 08:11

Java Developer


2 Answers

You cannot return separate structures via one method call, but you can return a composite of them. For example, returning a list of your lists would be a possible solution:

   public List<List<Date>> returnTwoArrayList()
   {
      List<Date> startDates = new ArrayList<Date>();
      List<Date> endDates = new ArrayList<Date>();

      List<List<Date>> result = new ArrayList<List<Date>>();
      result.add(startDates);
      result.add(endDates);

      return result;
   }

You can use get() method to retrieve these lists later on. Suppose you have made a call like List<List<Date>> twoLists = returnTwoArrayList(); then you can get startDate by calling twoLists.get(0) and similarly endDate with twoLists.get(1)

like image 134
Juvanis Avatar answered Dec 04 '22 15:12

Juvanis


No you can not return two value from a method.

Best way would be create a custom class with two field and return that object.

class ObjectHolder{
    private List<Date> startDate=new ArrayList<Date>();
    private List<Date> endDate=new ArrayList<Date>();

    <getter & setter method>
}

and -

public ObjectHolder returnTwoArrayList(){
    ObjectHolder oh = new ObjectHolder();
    List<Date> startDate=new ArrayList<Date>();
    oh.setStartDate(startDate);
    List<Date> endDate=new ArrayList<Date>();
    oh.setEndDate(endDate);
    return oh;
}
like image 39
Subhrajyoti Majumder Avatar answered Dec 04 '22 16:12

Subhrajyoti Majumder