简体   繁体   English

数据结构使所有元素处于特定位置

[英]Data Structure to get all elements at certain position

I have a square Grid with a certain height and width. 我有一个具有一定高度和宽度的正方形Grid It contains members of the class Item . 它包含Item类的成员。 Every Item has a certain Position . 每个Item都有特定的Position I'd like to be able to get all the items at a certain position in constant time, and I'd like to be able to place an item on the grid in amortized constant time. 我希望能够在恒定时间内将所有项目放置在某个位置,并且希望能够在摊销后的恒定时间内将项目放置在网格上。

What (Java) structure can do this while using an amount of memory proportional to the amount of used positions (positions with at least 1 item on it)? 当使用与使用的位置(上面至少包含一项的位置)的数量成比例的内存量时,什么(Java)结构可以做到这一点?

If your Grid has a fixed size I would use an array. 如果您的网格大小固定,我将使用数组。

Item[][] itemArray = new Item[3][3];
itemArray[0][0] = new Item();
System.out.println(itemArray[0][0]);

I would wrap that into the class Grid 我会将其包装到Grid类中

public final class Grid {

    private Item[][] grid;

    public Grid(int width, int height) {
        grid = new Item[width][height];
    }

    public void setItemAt(Position position, Item item) {
        int x = position.getX();
        int y = position.getY();

        grid[x][y] = item;
    }

    public Item getItemAt(Position position) {
        int x = position.getX();
        int y = position.getY();

        return grid[x][y];
    }
}

The user above is right that internally you can use an array. 上面的用户说的很对,您可以在内部使用数组。 Of course it should be of type List<Item>[][] . 当然,它应该是List<Item>[][] No matter if you use ArrayList or LinkedList , adding will be amortized constant time. 无论您使用ArrayList还是LinkedList ,添加都将摊销固定时间。 Though I would suggest going for a LinkedList , as your Grid is likely to be sparsely populated ( ArrayList always starts with a couple of spaces already allocated). 尽管我建议您使用LinkedList ,但是您的Grid很可能是稀疏填充的( ArrayList总是以几个已经分配的空格开始)。

If the Grid needs to be able to grow, just use the same trick ArrayList uses: keep track of current width/height, and if you need more just multiply available space by a suitable value (for a 2D array, doubling might be a bit much, but it depends on the type of growth that is possible). 如果Grid需要能够增长,请使用ArrayList的相同技巧:跟踪当前的宽度/高度,如果需要更多,只需将可用空间乘以合适的值(对于2D数组,可能需要加倍很多,但这取决于可能的增长类型)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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