Search code examples
javajpcap

Why can't I store arrays inside another array?


I code in c++ ever from the start but now have been working on project related to Network Administration on Java. Here a[i].addresses returns a NetworkInterfaceAddress[] (i.e., an array). But when I try to copy like this, it gives an error.

NetworkInterface[] a;  
a=JpcapCaptor.getDeviceList();  
NetworkInterfaceAddress[] b=new NetworkInterfaceAddress[a.length];  
int i=-1;  
while(++i<a.length)  
b[i]=a[i].addresses;  

This gives an error:

incompatible types: NetworkInterfaceAddress[] cannot be converted to NetworkInterfaceAddress.

Solution

  • The array b is a NetworkInterfaceAddress array, meaning that it can store objects of type NetworkInterfaceAddress. However, as you said, a[i].addresses returns an array of NetworkInterfaceAddress So, b should be capable of storing arrays of type NetworkInterfaceAddress instead of objects of type NetworkInterfaceAddress. For that, b should be an array of arrays or a jagged array. Change b's definition to

    NetworkInterfaceAddress[][] b = new NetworkInterfaceAddress[a.length][];
    

    Then, while adding a[i].addresses in the array, assign the length of the current array inside b, that has to hold a[i].addresses, to a[i].length.

    while(++i<a.length){
        b[i] = new NetworkInterfaceAddress[a[i].addresses.length];
        b[i] = a[i].addresses; //b[i] is an array itself
    }