Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create deep copy of array passed, if the array is valid?

Tags:

java

arrays

SO an IPv4 array is passed to this method, and if valid, creates a deep copy of the array in the instance variable "parts"

/**
 * If the ip address from the array passed (data) is valid,
 * makes a deep copy of the array passed in the instance variable parts.
 * For example, if data = {192,168,0,1}, parts should become {192,168,0,1}
 * by copying each item of data into corresponding item in parts.
 * If the ip address passed is invalid (for example {500,4,60,216}
 * or {192,16,01}, or {13,13,13,13,13}, parts should become {0,0,0,0}
 * 
 * remember to reset the instance array parts before you do anything else
 * @param data
 */
public void setParts(int[] data) {
this.parts = new int[4];
if (data.length != 4){
    parts = new int[]{0,0,0,0};
}
else
    for (int i = 0; i <= data.length; i++)
        if ((data[i] < 0) || (data[i] > 255))
            parts = new int[]{0,0,0,0};
        else
            parts[i] = data[i];
}

is all I have so far. What could I be missing?

EDIT: made one simple change:

for (int i = 0; i <= data.length; i++)

to

for (int i = 0; i < data.length; i++)

And a JUnit test

    public void testSetPartsIntArray() {
    correct1.setParts(new int[]{12, 14, 16, 18});
    int[] a = correct1.getParts();
    assertEquals(4, a.length);
    assertEquals(12, a[0]);
    assertEquals(14, a[1]);
    assertEquals(16, a[2]);
    assertEquals(18, a[3]); 

    correct1.setParts(new int[]{-12, 14, 16, 18});
    a = correct1.getParts();
    assertEquals(4, a.length);
    assertEquals(0, a[0]);
    assertEquals(0, a[1]);
    assertEquals(0, a[2]);
    assertEquals(0, a[3]);  

works UNTIL

assertEquals(0, a[1]);

What is causing it to stop there?

like image 872
Alonzo Robbe Avatar asked Sep 11 '16 06:09

Alonzo Robbe


People also ask

Which of the following array functions can be invoked to create a deep copy?

2. The functional programming library Ramda includes the R. clone() method, which makes a deep copy of an object or array.

Is array copy of a deep copy?

No, it does not. When you assign a new object to the "original" array, this does not affect the copy. It is, after all, a copy.


1 Answers

Once you find an invalid value, you must break from the loop :

for (int i = 0; i <= data.length; i++)
    if ((data[i] < 0) || (data[i] > 255)) {
        parts = new int[]{0,0,0,0};
        break;
    } else {
        parts[i] = data[i];
    }

In your failed case, the first element -12 is invalid, so parts is set to new int[]{0,0,0,0}, but then you continue the loop, and since the rest of the numbers are valid, you end up with {0, 14, 16, 18} instead of {0, 0, 0, 0}.

like image 157
Eran Avatar answered Sep 28 '22 11:09

Eran