简体   繁体   中英

Which element has been added to the ArrayList as last?

For example: I have an ArrayList composed of Points. Every point have an array of ints which defines his position. I can have few points in this same position and add them to my ArrayList at every index I want.

The question is:

I have given position and I want to check if any point of my ArrayList have this position. If yes, i return it. If there are few points with this position i need to return the last added (by time). Method equals won't work. I need to compare it with ==, so i need the correct the reference to the newest point.

How i should do it?

I should build another list of unique points, if in this list is another point with the same position I should replace it with newer?

public class Point {
    private final int DIMENSIONS;
    private final int[] position;

    public Point(int dimensions) {
        DIMENSIONS = dimensions;
        position = new int[DIMENSIONS];
    }

    public void setPosition(int dim, int value) {
        position[dim] = value;
    }

    public int getPosition(int dim) {
        return position[dim];
    }
}

You should use another or at least, an additional data structure.

ArrayLists are just that a List implementation that gives a you a list that grows dynamically. It doesn't care about insertion order.

If you need that, you should rather look to a LinkedHashMap. Of course, that alone won't work: you want that two Point objects that have the same position contents are in fact equal . So you could only have one such point in your Map.

That is what can be said given the current information. For more specific guidance, you should rather show us the relevant parts of the Point class implementation. For example: which elements do really go into your equals() implementation? That aspect alone drives how you should organize your data.

Well, one remark: if you add multiple "equal" Points to your list, and you just keep appending them to the end of your list, then you could simply search from the rear end. The first matching Point is also then one that was added last.

Edit, given the Point class implementation. Basically, that class is pointless. Either it is missing other attributes or it is missing reasonable equals/hashCode methods. Meaning: if a Point is really just that: a list of positions ... or it should be more than that.

But when a Point only contains positions, then that means: two points with equal positions should be equal. In other words: a Point class like this should definitely have value semantics . A Point(0, 1) should be equal to any other Point(0, 1)!

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