简体   繁体   中英

Adding an object to an arraylist causes the object's fields to become null

I have this code:

    blocks.clear();
    if(onStart.parts==null){System.out.println("null before");}
    blocks.add(onStart);
    if(blocks.get(0).parts==null){System.out.println("null after");}

where blocks is an initialized ArrayList<Block> , and parts is a field of Block of type ArrayList<BlockPart> . For some reason, that snippet of code only outputs " null after ". Why does the parts field become null?

EDIT: I have added the following code:

    System.out.println(blocks.get(0)==onStart?"same":"not same");
    System.out.println(blocks.get(0).parts==onStart.parts?"same":"not same");

The output is now:

same
not same

Strangely, the null after isn't showing in the console anymore.

EDIT 2: Replacing parts with name causes only null after to show. I don't know why the issue with the parts field somehow fixed itself. Before, I made the parts field final, but then removed the final modifier from it because I thought that I might want to change .parts later on. Now, it fixed itself. IDK why.

Your final statement:

System.out.println(blocks.get(0)==onStart?"same":"not same");
System.out.println(blocks.get(0).parts==onStart.parts?"same":"not same");

implies that it's something in your syntax that is changing the way your objects are being accessed. Break the second one down:

Block newblock=blocks.get(0)

then if newblock == onStart, newblock.parts MUST == onStart.parts

if that proves out then you can delve in to examining why the syntax doesn't chain together well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM