[英]How to shrink a Map in Java after deleting one of its elements (objects)?
假设我得到一个 map 表示为{[A, 0], [B, 1] [C, 2], [D, 3], [E, 4], [F, 5], [G, 6 ]}并删除其中一个元素,即[E, 4] ,那么我的新 map 将变为{[A, 0], [B, 1] [C, 2], [D, 3], [F , 5], [G, 6]} 。 我将如何调整或缩小这个 map 以便被删除元素之后的元素会像这样{[A, 0], [B, 1] [C, 2], [D, 3], [F, 4], [G, 5]} ? 除此之外,我将如何调整ArrayList<ArrayList<GraphEdge<L>>>
矩阵的大小?
注意:对节点的索引分配必须遵循插入顺序,因此插入图中的第一个节点必须分配索引 0,第二个节点分配索引 1,依此类推。
Java代码:
@Override
public void removeNode(GraphNode<L> node) {
if (node == null) {
throw new NullPointerException();
}
if (!this.nodesIndex.containsKey(node)) {
throw new IllegalArgumentException();
}
// Implement here
}
@Override
public boolean addNode(GraphNode<L> node) {
if (node == null) {
throw new NullPointerException();
}
if (this.nodesIndex.containsKey(node)) {
return false;
}
// Implement here
}
包含与其索引(值)关联的元素(键)的 map 表示如下:
/*
* A set of nodes in which every node is associated to its index in the adjacency
* matrix
*/
protected Map<GraphNode<L>, Integer> nodesIndex = new HashMap<GraphNode<L>, Integer>();
而矩阵表示如下:
/*
* The adjacency matrix in which its elements are null or objects of the class
* GraphEdge<L>. The use of ArrayList allows the matrix to resize
* gradually whenever a new object (element) is added or removed
* (deleted).
*/
protected ArrayList<ArrayList<GraphEdge<L>>> matrix = new ArrayList<ArrayList<GraphEdge<L>>>();
您不应该出于您的目的使用Map
。 映射条目配对的值部分与 map 中的条目 position 无关。 实际上,条目在 Map 中没有Map
!
如果要通过集合中从零开始的索引来跟踪对象,请使用List
。 每个列表都通过这样的索引跟踪添加。
List< Car > favoriteCars = new ArrayList<>(4) ;
favoriteCars.add( subaruBrz ) ;
favoriteCars.add( hondaElement ) ;
favoriteCars.add( jeepRenegade ) ;
favoriteCars.add( kiaSoul ) ;
获得第二喜欢的汽车。
Car secondFavoriteCar = favoriteCars.get( 1 ) ; // hondaElement.
但后来我们意识到本田元素不再生产。 所以从我们的名单中删除。
favoriteCars.remove( hondaElement ) ;
其余元素的索引位置向上移动以缩小差距。 询问第二喜欢的汽车现在将显示jeepRenegade
object。
Car secondFavoriteCar = favoriteCars.get( 1 ) ; // jeepRenegade.
使用 LinkedHashMap。 LinkedHashMap 是保持插入顺序的映射,而不是散列值,而是散列值链表中的节点。 然后,您可以遍历 map 中的所有键,直到找到匹配的键并在迭代中更改之后的所有值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.