【问题标题】:Naming Arraylists in a loop - Java在循环中命名 Arraylist - Java
【发布时间】:2012-11-07 20:29:29
【问题描述】:

我需要在 while 循环中创建一个 Arraylist,其名称也基于循环中的变量。这是我所拥有的:

while(myScanner.hasNextInt()){    

    int truster = myScanner.nextInt();
    int trustee = myScanner.nextInt();
    int i = 1;
    String j = Integer.toString(i);
    String listname = truster + j;

    if(listname.isEmpty()) {
        ArrayList listname = new ArrayList();
    } else {}
    listname.add(truster);

    i++;
}

变量 truster 在被扫描时会出现不止一次,所以 if 语句试图检查 arraylist 是否已经存在。不过,我想我可能做错了。

感谢您的帮助!

【问题讨论】:

  • 我不确定你为什么要动态命名一个对象。您能否详细说明是什么推动了这一请求?
  • 感谢您的回复。我正在尝试从 txt 文件中的数据创建数组列表的数组列表。因此扫描仪。
  • 这永远不会编译。我猜你想要一个 HashMap 来跟踪输入的信任者?
  • 请不要使用原始ArrayLists
  • 也许我读错了,但“i”不总是1吗?

标签: java loops arraylist


【解决方案1】:

将 ArrayList 存储在 Map 中:

Map<String, List<String> listMap = new HashMap<String,List<String>>();
while (myScanner.hasNextInt()){    
    // Stuff
    List<String> list = new ArrayList<String>();
    list.add(truster);
    listMap.put(listname, list);
}

注意使用泛型(&lt;&gt; 中的位)来定义 ListMap 可以包含的 Object 的类型。

您可以使用listMap.get(listname); 访问存储在Map 中的值

【讨论】:

【解决方案2】:

如果我理解正确,请创建一个列表列表,或者更好的是,创建一个映射,其中键是您想要的动态名称,值是新创建的列表。将其包装在另一个方法中并像 createNewList("name") 一样调用它。

【讨论】:

    【解决方案3】:

    真的完全不确定你的意思,但你的代码有一些严重的基本缺陷,所以我会解决这些问题。

    //We can define variables outside a while loop 
    //and use those inside the loop so lets do that
    Map trusterMap = new HashMap<String,ArrayList<String>>();
    
    //i is not a "good" variable name, 
    //since it doesn't explain it's purpose
    Int count = 0;
    
    while(myScanner.hasNextInt()) {    
        //Get the truster and trustee
        Int truster = myScanner.nextInt();
        Int trustee = myScanner.nextInt();
    
        //Originally you had:
        // String listname = truster + i;
        //I assume you meant something else here 
        //since the listname variable is already used
    
        //Add the truster concated with the count to the array
        //Note: when using + if the left element is a string 
        //then the right element will get autoboxed to a string
    
        //Having read your comments using a HashMap is the best way to do this.
        ArrayList<String> listname = new ArrayList<String>();
        listname.add(truster);
        trusterMap.put(truster + count, listname);
        i++;
    }
    

    此外,您在 myScanner 中存储了一个 Ints 流,这些 Ints 将被输入到数组中,但每个都有非常不同的含义(trustertrustee)。您是否尝试从文件或用户输入中读取这些内容?有更好的方法来处理这个问题,如果你在下面评论你的意思,我会更新一个建议的解决方案。

    【讨论】:

    • 感谢您的回复。是的,我对前几节课很熟悉,但我试图在循环内创建数组列表,然后将每个数组列表放在一个大数组列表中。我正在使用扫描仪读取一个大整数文件。
    • 太苛刻了,抱歉。最好的方法是使用 HashMap。然后您可以使用 trusterMap.get([trustername+count]) 来获取列表。或者使用迭代器,因为您不会确切地知道键。
    猜你喜欢
    • 2018-01-15
    • 2019-07-26
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-22
    相关资源
    最近更新 更多