0

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.
progyammer
  • 1,498
  • 3
  • 17
  • 29
  • 3
    I think a[i].addresses; is returning an array of NetworkInterfaceAddress. can you check? – Lyju I Edwinson Oct 19 '16 at 05:55
  • Yes it does according to the link : http://jpcap.gitspot.com/javadoc/jpcap/NetworkInterface.html#addresses. And I want all those addresses to be stored in b. – Abhimanyu Kaushal Oct 19 '16 at 06:07
  • Ok then you need to copy it in to an Array for this `NetworkInterfaceAddress[] b=new NetworkInterfaceAddress[a.length];` you can have one instance of NetworkInterfaceAddress in each column. So you can't store it there. – Lyju I Edwinson Oct 19 '16 at 06:26

1 Answers1

0

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
}
progyammer
  • 1,498
  • 3
  • 17
  • 29
  • 2
    You are assigning twice to `b[i]`, so the first value is being overwritten immediately. Decide whether you want to copy the array contents (which you don’t in your current code) or it suffices to copy the array reference (for which the second assignment is enough). – Ole V.V. Oct 19 '16 at 06:28
  • @OleV.V. Yeah, actually, I wanna do what the second assignment alone does. I didn't realize that it can do it alone what I'm trying to do; I'm habituated to preventing `NullPointerException`s for object arrays, which I need not worry about for jagged arrays. That's why I first initialized `b[i]` – progyammer Oct 19 '16 at 06:40
  • Thanks for clarifying. You IDE ought to tell you that the first value assigned is never used (or you have not set up its warnings properly :-) – Ole V.V. Oct 19 '16 at 06:46