Home > Enterprise >  Does the Android studio modify the parameter values?
Does the Android studio modify the parameter values?

Time:05-01

During the creation of the calendar app, the calendar variable representing the current date was set as a parameter. I copied it to a calendar variable called cal, and in the process of changing the date of cal to 1, the selectedDate variable also changes to one day.

    public ArrayList<String> setCalendarDate(Calendar selectedDate){
    ArrayList <String> dateArray = new ArrayList();
    Calendar cal = selectedDate;
    Log.e("cp_1", String.valueOf(selectedDate.get(Calendar.DATE)));
    cal.set(Calendar.DATE,1);
    Log.e("cp_2", String.valueOf(selectedDate.get(Calendar.DATE)));
    int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK)-1;
    int lengthOfMonth = cal.getActualMaximum(Calendar.DATE);
    for (int i = 1; i <= 42; i  ) {
        if(i<= dayOfWeek || i> (lengthOfMonth   dayOfWeek))
            dateArray.add("");
        else dateArray.add(String.valueOf(i-dayOfWeek));
    }
    return dateArray;
}

this is the function.

CodePudding user response:

When you pass an argument to a function, you're passing a reference to a variable. You're not making a copy of the object being referenced, you're just passing a pointer to it. When you set cal=selectedDate, you're doing the same thing- setting a reference to the object, not copying it. That means that selectedDate and cal both point to the same object. So changing one will change both (since they're the same thing). If you want to make a copy so changing one doesn't change the other, you need to do so explicitly. Calendar provides the clone() method which creates a copy of the object. So change your code to cal=selectedDate.clone() if you wish to make a copy that can be changed without changing the original.

  • Related