[英]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.