I have a method that should add several days to the selected date, it looks like this

private String changeDate(int addDays) { Calendar calendar = mCalendar; calendar.add(Calendar.DAY_OF_YEAR, addDays); SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy"); String date = format.format(calendar.getTime()); return date; } 

where mCalendar is a global variable of type Calendar . The bottom line is that every time the mCalendar method is mCalendar , for some reason it also adds the number of days to itself, although in the code I add days only to the variable calendar . What could be the problem, is there any problem with the Calendar type in the Android SDK?

    1 answer 1

    The variables сalendar and mCalendar have the same reference. And if you change one of them, the other changes. These are java features, not Android.

    UPDATE: Replace

     Calendar calendar = mCalendar; 

    on

     Calendar calendar = (Calendar)mCalendar.clone(); 
    • Hah, everything is so simple ... Do not tell me then how to solve this problem? - user214046
    • @ Alexander Answer supplemented. - iramm
    • Thank you, it works! - user214046
    • @ Alexander Not at all :) - iramm