2

I am writing a code where i have to add a 1d array in 2d array. For example: I have a userlist array which will add data array in it

Double[][] userList =  new Double[4][appName.size()];
Double[] data = new Double[appName.size()];

so user list will have something like this:

userlist={{1,2,3,4},  {2,3,4,7},  {0,0,1,2,}}

where {1,2,3,4}===> represents data array.

Problem: The problem that i am getting is that each time what data array returns just overwrite the whole thing in userlist with the new data.

for example:

if userlist={{1,2,3,4},  {2,3,4,7}} and data returns {0,0,4,5}
then my userlist becomes: {{0,0,4,5}, {0,0,4,5}, {0,0,4,5} }.

Code:

Double[][] userList = null;
userList = new Double[4][appName.size()];
String prevName = null;
Double[] data = new Double[appName.size()];
int count=0;

   for(AuditInformationEntity e : auditInfoList)
   {
    //int count =0;

    if(prevName== null || !prevName.equals(e.getDisplayName()) )
    {

        if(prevName!=null)
        {

        ////====>> I think Something to be done here<========/////  
            userList[count++]=data;
        }
        //data = new ArrayList<Double>();
        for(int i = 0 ; i<appName.size();i++)
            data[i]=0d;
        prevName = e.getDisplayName();
    }
    Double d = data[appName.indexOf(e.getAppName())];

    if(d==null){
        d=1d;
        data[appName.indexOf(e.getAppName())]= d;
    }
    else
    {
        d++;
        data[appName.indexOf(e.getAppName())]= d;

    }


}
   userList[count++]=data;



       return userList;
2
  • Is this whole code in a method? Commented Sep 20, 2013 at 9:02
  • yes it is in a method.. Commented Sep 20, 2013 at 9:09

1 Answer 1

1

You've correctly identified the problem line. Java doesn't technically have multidimensional arrays; instead, it has arrays of arrays. This means that when you say userList[i] = data, you're just telling Java to update the reference of userList[i] to point to the same data array. (This is called an aliasing bug, since you are thinking you're dealing with different arrays, but you're just calling the same array by different names.)

Instead, in this case it's probably better to do this:

int i;
double userList[][] = new double[numberOfArrays][];
double data[] = new double[4];
...
    // inside a loop
    // read into data
    userList[i] = Arrays.copyOf(data);

This doesn't actually allocate the inside 4-element arrays when you create userList; it makes copies of each version of the data array when you're adding it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.