Home » Java » java – Prevent from changing the values in array-Exceptionshub

java – Prevent from changing the values in array-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

In my program I am creating an array which contains values of year-month-date. I assign them the values 2019, 6 and 17. As of now, the program allows me to change the value (see the comment in main). But i do not want this to be possible, how can i prevent this?

    public static void main (String[] args)
    {
        Date date = new Date (2019, 6, 17);
        date.printDate ();

        int[] dateValue = date.getDate ();
        dateValue[2] = 35; //Changes the value from 17 to 35. Is not suppose to happen.

        date.printDate ();
    }
public class Date
{
    private int[] ymd = new int[3];
    public Date (int year, int month, int day)
    {
        ymd[0] = year;
        ymd[1] = month;
        ymd[2] = day;
    }

    public int[] getDate ()
    {
      return ymd;
    }

    public void printDate ()
    {
        System.out.println (ymd[0] + "-" + ymd[1] + "-" + ymd[2]);
    }
}
How to&Answers:

Change getDate() to return a copy of the private array instance variable:

public int[] getDate ()
{
  return Arrays.copyOf(ymd,ymd.length);
}

This way callers of the method cannot mutate the state of the Date instance by modifying the returned array.

Answer:

Change getDate as follows:

public int[] getDate() {
    int[] newDate = new int[ymd.length];
    System.arraycopy(ymd, 0, newDate, 0, ymd.length);
    return newDate;
}