有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何在Java中存储项目的“多条信息”

我需要一个数据结构,将允许我存储每个项目至少2条数据。我希望项目按插入顺序存储

例如:

Insert (xyz, string) ... insert (789, number)
System.out.println( dataStruct );

将打印出(xyz, string),然后(789,number)

如果可能,请显示一些示例代码。谢谢大家!


共 (4) 个答案

  1. # 1 楼答案

    这将以某种方式满足需求,您还可以在HashMap的构造函数中使用该类型的参数

    HashMap map= new HashMap();
    List<HashMap> virtualDs= new ArrayList<HashMap>();
    
  2. # 2 楼答案

    以下代码可以是您的数据结构:

     List<Item> list;
    
        class Item {
         public String desc;
         public Integer val;
         void insert(String desc,Integer val){
         this.desc = desc;
         this.val = val; 
         }   
         void insert(Integer val,String desc){
         insert(desc,val);
         }
        }
    
  3. # 3 楼答案

    可以使用HashtableList

    例如:

    Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();
    //adding or set items in Hashtable by put method key and value pair
    hTable.put(new Integer(2), "Two");
    hTable.put(new Integer(1), "One");
    hTable.put(new Integer(4), "Four");
    hTable.put(new Integer(3), "Three");
    hTable.put(new Integer(5), "Five");
    

    看看一些Java structures

    编辑

    为了保持插入顺序,可以使用LinkedHashSetLinkedHashMap

  4. # 4 楼答案

    public class Store {
    String str1;
    String str2;
    
    public Store(String string1, String string2) {
        str1 = string1;
        str2 = string2;
    }
    
    public static void main(String[] args) {
    
        Store[] s = new Store[10]; // size
        for (int i = 0; i < s.length; i++) {
            s[i] = new Store("A", "B");
            System.out.println(s[i].str1);
            System.out.println(s[i].str2);
    
        }
    
    }
    }
    

    我想这就是你要找的。这是C型结构。试试这个。 这将帮助您只需做一些小的更改,就可以为每个项目插入2条以上的数据。秩序也将得到维持