Java 以下场景中使用的最佳数据结构(如哈希映射/列表等)是什么

Java 以下场景中使用的最佳数据结构(如哈希映射/列表等)是什么,java,list,data-structures,hashmap,Java,List,Data Structures,Hashmap,我有一个要求,比如有一个项目a,它有几个子项目,比如a1,b1,c1。。。每个子项依次有几个子项,如{a11,a12,a13…}对应a1和{b11,b12,b13…}对应b1。因此,它基本上类似于一个以项目a为根的树结构。现在,每个项目及其子项目都有一些时间戳。所有这些项目和子项目的时间戳都不同。我需要找到带有最新时间戳的项目/子项目。如何在java中继续解决这个问题。我对使用数据结构有点陌生。JDK中实现了一个不错的树结构 请看一下TreeModel和TreeNode,它们设计用于JTreeP

我有一个要求,比如有一个项目a,它有几个子项目,比如a1,b1,c1。。。每个子项依次有几个子项,如{a11,a12,a13…}对应a1和{b11,b12,b13…}对应b1。因此,它基本上类似于一个以项目a为根的树结构。现在,每个项目及其子项目都有一些时间戳。所有这些项目和子项目的时间戳都不同。我需要找到带有最新时间戳的项目/子项目。如何在java中继续解决这个问题。我对使用数据结构有点陌生。

JDK中实现了一个不错的树结构

请看一下
TreeModel
TreeNode
,它们设计用于
JTreePanel
,但是没有什么可以阻止您在Swing之外使用它。

使用

它会满足你的需要。下面是java.samples.com上的一个示例程序

// Create a tree map 
TreeMap tm = new TreeMap(); 
// Put elements to the map 
tm.put("John Doe", new Double(3434.34)); 
tm.put("Tom Smith", new Double(123.22)); 
tm.put("Jane Baker", new Double(1378.00)); 
tm.put("Todd Hall", new Double(99.22)); 
tm.put("Ralph Smith", new Double(-19.08)); 
// Get a set of the entries 
Set set = tm.entrySet(); 
// Get an iterator 
Iterator i = set.iterator(); 
// Display elements 
while(i.hasNext()) { 
Map.Entry me = (Map.Entry)i.next(); 
System.out.print(me.getKey() + ": "); 
System.out.println(me.getValue()); 
} 
System.out.println(); 
// Deposit 1000 into John Doe's account 
double balance = ((Double)tm.get("John Doe")).doubleValue(); 
tm.put("John Doe", new Double(balance + 1000)); 
System.out.println("John Doe's new balance: " + 
tm.get("John Doe"));

假设没有B项:

  • 存储项目A、项目B、项目C。。。在链接列表中。(每个节点成为根节点)
  • 项目A将具有以下子节点:a1、b1、c1。。。在链接列表中。(每个节点成为根节点)
  • a11、a12、a13可以存储为a1的子节点
  • 与b11、b12、b13类似

  • 现在,您面临的问题在哪里?

    有关数据结构,请查看
    java.util.TreeMap
    以了解树支持的映射实现,以及
    java.util.TreeSet
    以了解树支持的集实现。这些是Java Collections API中的标准实现

    package com.mindprod.example;
    
    import java.util.Collection;
    import java.util.Map;
    import java.util.Set;
    import java.util.TreeMap;
    
    import static java.lang.System.out;
    
    /**
     * Example use of java.util.TreeMap.
     *
     * @author Roedy Green, Canadian Mind Products
     * @version 1.0 2010-02-25 initial version
     * @see TestHashMap
     * @since 2010-02-25
     */
    public final class TestTreeMap
    {
    // --------------------------- main() method ---------------------------
    
    /**
     * Sample code to TEST TreeMap.
     *
     * @param args not used
     */
    public static void main( String[] args )
        {
        // create a new HashMap
        TreeMap<String, String> t = new TreeMap<String, String>( /* no size estimates needed */ );
        // add some key/value pairs to the TreeMap
        t.put( "WA", "Washington" );
        t.put( "NY", "New York" );
        t.put( "RI", "Rhode Island" );
        t.put( "BC", "British Columbia" );
        t.put( "NC", "North Carolina" );
        t.put( "NE", "Nebraska" );
        // look up a key in the TreeMap
        String stateName = t.get( "NY" );
        // prints "New York"
        out.println( stateName );
        out.println( "enumerate all the keys in the TreeMap, by key" );
        // keySet gives you a Set, which is not a List.
        // If you need something you can sort, use toArray.
        // If you need a List, then use Arrays.asList.
        for ( String key : t.keySet() )
            {
            String value = t.get( key );
            // prints lines of the form NY New York
            // in key order, unlike a HashMap
            out.println( key + " " + value );
            }
        out.println( "enumerate all the values in the TreeMap, by key, note values out of order" );
        // values gives you a Collection which is not a List.
        // If you need something you can sort, use to Array.
        // If you need a List, then use Arrays.asList.
        for ( String value : t.values() )
            {
            // prints lines of the form New York
            // in key order, unlike a HashMap
            out.println( value );
            }
        out.println( "enumerate all the key/value Entries in the TreeMap, by key" );
        // This gives you a Map of Entry items. This is not suitable for sorting.
        for ( Map.Entry<String, String> entry : t.entrySet() )
            {
            // prints lines of the form NY=New York
            // in key order, unlike a HashMap
            out.println( "as Entry: " + entry );
            // this does not require an expensive get lookup to find the value.
            String key = entry.getKey();
            String value = entry.getValue();
            out.println( "separately: " + key + " " + value );
            }
        out.println( "extract the keys into an array" );
        // actual type is a private nested static class TreeMap.KeySet
        // This Set is not Serializable.
        Set<String> justKeys = t.keySet();
        // Use toArray that takes an skeleton String[] array,
        // otherwise we end up with a useless Object[] instead of a String[].
        final String[] keys = justKeys.toArray( new String[ justKeys.size() ] );
        out.println( "extract values into an array, may contain duplicates unlike a Set." );
        // the actual type is a private nested static class TreeMap.Values
        // This Collection is not Serializable.
        final Collection<String> justValues = t.values();
        final String[] values = justValues.toArray( new String[ justValues.size() ] );
        out.println( "extract key/value pair entries into an array." );
        final Set<Map.Entry<String, String>> justEntries = t.entrySet();
        @SuppressWarnings( "unchecked" ) final Map.Entry<String, String>[] keyValuePairs =
                justEntries.toArray( new Map.Entry[ justEntries.size() ] );
        // Infuriatingly, this generates an unchecked conversion warning message.
        // Type erasure won't let us say:
        // Map.Entry<String, String>[] keyValuePairs =
        // justEntries.toArray ( new Map.Entry<String,String>[justEntries.size()] );
        // There might be some clever way of using Class.asSubclass to mollify the compiler.
        // There so many times when generics create more problems than they solve.
        }
    }
    
    package com.mindprod.example;
    导入java.util.Collection;
    导入java.util.Map;
    导入java.util.Set;
    导入java.util.TreeMap;
    导入静态java.lang.System.out;
    /**
    *java.util.TreeMap的示例使用。
    *
    *@作者Roedy Green,加拿大Mind Products
    *@version 1.0 2010-02-25初始版本
    *@请参阅TestHashMap
    *@自2010年2月25日起
    */
    公共最终类TestTreeMap
    {
    //------------------------------------main()方法---------------------------
    /**
    *测试TreeMap的示例代码。
    *
    *@param参数未使用
    */
    公共静态void main(字符串[]args)
    {
    //创建一个新的HashMap
    TreeMap t=新的TreeMap(/*无需尺寸估算*/);
    //向树映射添加一些键/值对
    t、 put(“WA”、“华盛顿”);
    t、 出售(“纽约”、“纽约”);
    t、 put(“RI”,“罗德岛”);
    t、 put(“卑诗省”、“不列颠哥伦比亚省”);
    t、 出售(“北卡罗来纳州”、“北卡罗来纳州”);
    t、 put(“东北”、“内布拉斯加州”);
    //在树形图中查找一把钥匙
    字符串stateName=t.get(“NY”);
    //打印“纽约”
    out.println(stateName);
    println(“按键枚举树映射中的所有键”);
    //keySet为您提供一个集合,它不是列表。
    //如果您需要可以排序的内容,请使用toArray。
    //如果需要列表,请使用Arrays.asList。
    for(字符串键:t.keySet())
    {
    字符串值=t.get(键);
    //打印纽约表格的线条
    //按键顺序,与哈希映射不同
    out.println(键+“”+值);
    }
    println(“按键枚举树映射中的所有值,按顺序记录值”);
    //值提供的集合不是列表。
    //如果需要可以排序的内容,请使用数组。
    //如果需要列表,请使用Arrays.asList。
    for(字符串值:t.values())
    {
    //打印纽约表格的线条
    //按键顺序,与哈希映射不同
    out.println(值);
    }
    println(“按键枚举树映射中的所有键/值项”);
    //这将为您提供条目的地图。这不适合排序。
    for(Map.Entry:t.entrySet())
    {
    //打印形式为NY=纽约的行
    //按键顺序,与哈希映射不同
    out.println(“as Entry:+Entry”);
    //这不需要昂贵的get查找来查找值。
    String key=entry.getKey();
    字符串值=entry.getValue();
    out.println(“单独:“+键+”+值);
    }
    println(“将密钥提取到数组中”);
    //实际类型是私有嵌套静态类TreeMap.KeySet
    //此集合不可序列化。
    设置justKeys=t.keySet();
    //使用接受骨架字符串[]数组的数组,
    //否则,我们将得到一个无用的对象[],而不是字符串[]。
    最终字符串[]keys=justKeys.toArray(新字符串[justKeys.size()]);
    println(“将值提取到数组中,可能包含与集合不同的重复项。”);
    //实际类型是私有嵌套静态类TreeMap.Values
    //此集合不可序列化。
    最终集合justValues=t.values();
    最终字符串[]值=justValues.toArray(新字符串[justValues.size()]);
    println(“将键/值对条目提取到数组中”);
    最终设置justEntries=t.entrySet();
    @SuppressWarnings(“未选中”)最终映射。条目[]keyValuePairs=
    toArray(新的Map.Entry[justEntries.size()]);
    //令人恼火的是,这会生成一条未经检查的转换警告消息。
    //类型擦除不会让我们说:
    //Map.Entry[]keyValuePairs=
    //justEntries.toArray(新的Map.Entry[justEntries.size()]);
    //可能有一些聪明的方法可以使用Class.asSubclass来缓和编译器。
    //很多时候,泛型产生的问题比它们解决的问题还多。
    }
    }
    

    您也可能对此感兴趣

    我建议您为Item创建一个类,然后您可以单独设计该类

    由于子项取决于数据类型,请选择不同的数据结构。 首先,如果您知道项目的类型相同,例如a1、b1、c1都是字符串,则可以使用ArrayList保存它们,或者如果总数有界,则使用array。如果它们是不同类型的,那么考虑HASMAP。

    可以简单使用。

    ArrayList list=new ArrayList();
    ArrayList sublist=new ArrayList();
    ArrayList subsublist=new ArrayList();
    subsublist.add("cat");
    sublist.add(subsublist);
    list.add(sublist);
    
    public class Node
      {
        private String name;
        private Node parentNode;
        private Node childNode;
      }
    
    public Node(String name)
      {
        this.name = name;
        this.parentNode = null;
        this.childNode = null;
      }
    
    public class Item implements Comparable<Item>{
    
        private String name;
        private long timestamp;
        private List<Item> subItems = new ArrayList<Item>();
    
        public Item(String name, long timestamp){
            this.name = name;
            this.timestamp = timestamp;
        }
    
        public void addItem(Item subItem){
            this.subItems.add(subItem);
        }
    
        @Override
        public int compareTo(Item o) {
            return Long.signum(this.timestamp - o.timestamp);
        }
    
    }