Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Does the Android studio modify the parameter values?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading