简体   繁体   中英

How can two Java list elements access each other?

The root of the problem for me is that Java does not allow references.

The problem can be summarized succinctly. Imagine you have a List of Blob objects:

class Blob {
    public int xpos;
    public int ypos;
    public int mass;
    public boolean dead;
    private List<Object> giganticData;
    public void blobMerge(Blob aBlob) {
        . . .
        if (. . .) {
            this.dead = true;
        } else {
            aBlob.dead = true;
        }
    }
}

If two blobs are close enough, they should be merged, meaning one of the two blobs being compared should take on the attributes of the other (in this case, adding the mass and merging the giganticData sets) and the other should be marked for deletion from the list.

Setting aside the problem of how to optimally identify adjacent blobs, a stackoverflow question in its own right, how do you keep the blobMerge() logic in the Blob class? In C or C++ this would be straightforward, as you could just pass one Blob a pointer to the other and the "host" could do anything it likes to the "guest".

However, blobMerge() as implemented above in Java will operate on a copy of the "guest" Blob, which has two problems. 1) There is no need to incur the heavy cost of copying giganticData, and 2) the original copy of the "guest" Blob will remain unaffected in the containing list.

I can only see two ways to do this:

1) Pass the copies in, doing everything twice. In other words, Blob A hosts Blob B and Blob B hosts Blob A. You end up with the right answer, but have done way more work than necessary.

2) Put the blobMerge() logic in the Class that contains the containing List. However, this approach scales very poorly when you start subclassing Blob (BlueBlob, RedBlob, GreenBlob, etc.) such that the merge logic is different for every permutation. You end up with most of the subclass-specific code in the generic container that holds the list.

I've seen something about adding References to Java with a library, but the idea that you have to use a library to use a Reference put me off that idea.

Why would it operate on a copy? Java passes references to objects. And references are very much like C++ pointers.

Um... a reference is passed not a copy of the entire object. The original object will be modified and no data is actually moved around.

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