0

I've an array of objects:

Tratam --> has String, int ect.. and a Date object.

I want to add to a ArrayList 3 identical objects of each with different values of Date..

I have scheduled the following code, but as result in the arraylist always add the objects with the last date.. For example: If the dates must be 3:05, 3:15 and 3:25, add the objects with the third value.

Does anyone know what I'm doing wrong?

Thanks in advance!!!

for(n=0;n<tam;n++){
    addObj(arrayObj[n]);
}


public void addObj(Tratam trat){
    Tratam [] arrayObj2 = new Tratam[3];
    Date date=trat.getNextTime();
    for(int n=0;n<3;n++){
        arrayObj2[n]=trat;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.SECOND, interval);
        date=cal.getTime();
        arrayObj2[n].setNextTime(date);

        arrayListTrat.add(arrayObj2[n]);
        }

    }

1 Answer 1

1

A simple check on you code tells me that, you are adding same object again in the list. That is why you are getting same time.

This is what I did to check that.

public void addObj(Tratum trat) {
        Tratum[] arrayObj2 = new Tratum[3];
        Date date = trat.getNextTime();
        for (int n = 0; n < 3; n++) {
            arrayObj2[n] = trat; // I think this line is the culprit
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            cal.add(Calendar.SECOND, n + 1000 * n);
            date = cal.getTime();
            Log.d("inTemp","" + date.toString());

            arrayObj2[n].setNextTime(date);
            if(n ==1){
                if(arrayObj2[n].equals(arrayObj2[n-1])){
                    Log.d("TEMP","$$Equal");
                }
            }
            arrayListTrat.add(arrayObj2[n]);
        }

Try this:

Instead of doing this.

arrayObj2[n] = trat;

Try to do like this,

arrayObj2[n] = new Tratum();
   arrayObj2[n].setNextDate(trat.getNextDate()); // In short rather than assigning object trat to your array object. Simply assign values. 

This should solve your issue.

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.