简体   繁体   English

Java:ArrayList <HashMap<Integer,Integer> &gt;

[英]Java : ArrayList<HashMap<Integer,Integer>>

Is there a better approach to do the below in Java, without using external libraries. 有没有更好的方法在Java中执行以下操作,而不使用外部库。

I need to model group/child (tree like) structure of int (primitive). 我需要模拟int(primitive)的group / child(tree like)结构。 In Json 在Json

[{1,1}, {1,2}, {2,1},{3,1}]

I need to support addition/removal of elements (element is a pair {group, child} ) without duplication. 我需要支持添加/删除元素(元素是一对{group,child})而不重复。

I am thinking of, keeping a data structure like. 我在考虑,保持数据结构。

ArrayList<HashMap<Integer,Integer>>

To add. 加上。

Iterate through ArrayList, check HashMap key and value against the value to insert, and insert if not exist. 通过ArrayList迭代,检查HashMap键和值以插入值,如果不存在则插入。

To delete: 删除:

Iterate through ArrayList, check HashMap key and value against the value to delete, and delete if exist. 通过ArrayList迭代,检查HashMap键和值以删除值,如果存在则删除。

Is there a better data structure/approach with standard library. 是否有更好的数据结构/方法与标准库。


As per one of the answer below, I made a class like this. 根据下面的答案之一,我做了一个这样的课程。 Please let me know anything to watchout. 请让我知道任何要注意的事项。 I am expecting (and going to try out) arraylist would handle add/remove correctly by using the equal method in KeyValue class. 我期待(并试图)arraylist将通过使用KeyValue类中的equal方法正确处理添加/删除。 thanks. 谢谢。

 static class KeyValue {
        int groupPos;
        int childPos;

        KeyValue(int groupPos, int childPos) {
            this.groupPos = groupPos;
            this.childPos = childPos;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            KeyValue keyValue = (KeyValue) o;

            if (childPos != keyValue.childPos) return false;
            if (groupPos != keyValue.groupPos) return false;

            return true;
        }

        @Override
        public int hashCode() {
            int result = groupPos;
            result = 31 * result + childPos;
            return result;
        }
    }

If I understand what you're trying to do, this may be simpler: 如果我理解你要做什么,这可能会更简单:

TreeMap<Integer,TreeSet<Integer>>
  or
HashMap<Integer,HashSet<Integer>>

So, rather than 所以,而不是

[{1,1}, {1,2}, {2,1}, {3,1}]

you'd have 你有

[{1, {1, 2}},
 {2, {1}},
 {3, {1}}]

Note that all 4 of the above classes automatically handles eliminating duplicates. 请注意,上述所有4个类都自动处理消除重复项。

To add: 加上:

TreeMap<Integer, TreeSet<Integer>> map;
TreeSet<Integer> set = map.get(group);
if (set == null) // create it if it doesn't exist
{
  set = new TreeSet<Integer>();
  map.put(group, set);
}
set.add(child);

To remove: 去除:

TreeMap<Integer, TreeSet<Integer>> map;
TreeSet<Integer> set = map.get(group);
set.remove(child);
if (set.isEmpty()) // remove it if it is now empty
  map.remove(group);

You may write a class with name KeyValue with two properties to hold group and child. 您可以编写一个名为KeyValue的类,其中包含两个属性来保存组和子项。 Add KeyValue Objects to ArrayList . KeyValue对象添加到ArrayList For CRUD operations, you may implement equals and compare in your KeyValue pair class. 对于CRUD操作,您可以在KeyValue对类中实现equalscompare

Instead of HashMap , use a class called Pair with two fields {group,child} which will implement Comparable interface. 而不是HashMap ,使用一个名为Pair的类,其中两个字段{group,child}将实现Comparable接口。 Then implement/override its equals() , hashCode() and compareTo() methods. 然后实现/覆盖其equals()hashCode()compareTo()方法。 Then use either a List<Pair> or Set<Pair> depending on your needs to hold them. 然后根据您的需要使用List<Pair>Set<Pair>来保存它们。 Having compareTo() implemented gives you the flexibility to sort Pairs easily too. 实现compareTo() ,您可以轻松地对Pairs进行排序。

I am new to the Data Structure world but I think we can use this based on the assumption that no two Set Objects will be similar 我是数据结构世界的新手,但我认为我们可以在没有两个Set Objects相似的假设下使用它

Set validSet=new HashSet(); 设置validSet = new HashSet(); // Use Generics here //在这里使用泛型

HashSet will provide a constant time for add/delete/contains HashSet将为添加/删除/包含提供一个恒定的时间

SomeObject{
     Integer parent ;
     Integer child;
     //define equals method based on your requirement
}

Going By your Question i think that You want to show this line 继续你的问题我认为你想要显示这一行

[{1,1}, {1,2}, {2,1},{3,1}]

as

Group 1-> 1 , 2 (from first two pair) 组1-> 1,2(前两对)
Group 2-> 1(from third pair) 组2-> 1(来自第三对)
Group 3-> 1 (from fourth pair) 组3-> 1(来自第四对)

The data structure that suites most for storing this hierarchy is : 最适合存储此层次结构的数据结构是:

Map<Integer,Set<Integer>> map = new HashMap<Integer,Set<Integer>>();

Where the key part of map stores the group Number. 地图的key部分存储组号。 And the value part of map is storing TreeSet which stores the children of that group. 而map的value部分是存储TreeSet ,它存储该组的子TreeSet
As Example of code: 作为代码示例:

import java.util.HashMap;
import java.util.ListIterator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
class  TreeLike
{
    public static void main(String[] args) 
    {
        Map<Integer,Set<Integer>> map = new HashMap<Integer,Set<Integer>>();
        int groups[] = {1,2,3,4,5,6,7};
        //To add new group in map
        for (int i = 0 ; i < groups.length; i++)
        {
            Set<Integer> child = new TreeSet<Integer>();
            child.add(1);child.add(2);child.add(3);child.add(4);child.add(5);
            map.put(groups[i],child);
        }
        //To add new child(8) to a group (say group 1)
        Set<Integer> child = map.get(1);
        if (child != null)
        {
            child.add(8);
            map.put(1,child);
        }

        //To remove a child (say child 4) from group 3
        child = map.get(3);
        if (child != null)
        {
            child.remove(4);
            map.put(1,child);
        }
        //To Iterate through all trees
        Set<Map.Entry<Integer,Set<Integer>>> entrySet = map.entrySet();
        Iterator<Map.Entry<Integer,Set<Integer>>> iterator = entrySet.iterator();
        while (iterator.hasNext())
        {
            Map.Entry<Integer,Set<Integer>> entry = iterator.next();
            int group = entry.getKey();
            Set<Integer> children = entry.getValue();
            System.out.println("Group "+group+" children-->"+children);
        }
    }
}

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

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