Calendar - strange behavior



  • I have a method to add to my chosen date for a few days, it looks like it.

    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 - Global variable type Calendar♪ The point is that each method of implementation mCalendar And somehow adds that number of days to me, even though in the code I add days to the variable only. calendar♪ What's the problem, is there a type? Calendar Android SDK any underwater stones?



  • Removed сalendar and mCalendar have the same reference. And if you change one of them, the other changes. It's java, not Android.

    UPDATE: Replace

    Calendar calendar = mCalendar;
    

    Calendar calendar = (Calendar)mCalendar.clone();
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2