【问题标题】:Accessing data from an Arraylist stored in an Arraylist - Java从存储在 Arraylist 中的 Arraylist 访问数据 - Java
【发布时间】:2013-09-04 06:35:43
【问题描述】:

我正在尝试访问存储在 Arraylist 中的 Arraylist 中的数据。我确信有一种非常简单的方法可以做到这一点,我不想浪费任何人的时间,但我尝试了很多方法,似乎无法在任何地方找到答案。任何帮助将非常感激。

这是我创建数组的代码。

    public ArrayList SGenresMaster = new ArrayList(new ArrayList());
    public ArrayList S1Genres = new ArrayList();
    public ArrayList S2Genres = new ArrayList();
    public ArrayList S3Genres = new ArrayList();        


    public void accessArrays(){

    SGenresMaster.add(S1Genres);
    SGenresMaster.add(S2Genres);  
    SGenresMaster.add(S3Genres);

    }

基本上我需要能够使用 SgenresMaster 访问 S1Genres 的任何索引。

到目前为止,我只设法将数据作为长字符串取出,所以我想我会发布我当前的方法来获取我需要的数据,因为我认为这可能会让专业人士在这里畏缩/大笑。

    createarray(SGenresMaster.get(i).toString());

    public ArrayList createarray(String string){

    String sentence = string;
    String[] words = sentence.split(", ");
    ArrayList temp = new ArrayList();
    int b = 0;
    for (String word : words)
    {
        if (b == 0){
            //Delete First bracket
            temp.add(word.substring(1,word.length()));
            System.out.println("First Word: " + temp);
        }
        else{
            temp.add(word.substring(0,word.length()));
            System.out.println("Middle Word: " + temp);
        }
        b++;

    }
    //Delete last bracket
    String h = String.valueOf(temp.get(temp.size() - 1));
    temp.add(h.substring(0,h.length() - 1));
    temp.remove(temp.size() - 2);


    System.out.println("final:" + temp);

    return temp;
} 

【问题讨论】:

  • 我认为您的主要问题是使用原始数组列表,请使用 表示法来指示它们包含的内容
  • 确实,你不使用 Java 泛型有什么原因吗?
  • 除了不知道我需要这样做之外,没有任何理由。为帮助干杯。
  • @GregKing 除了解决这个问题之外,它还避免了从数组列表中强制转换 .get() 的东西,并为您提供类型安全。总而言之,始终使用非原始版本

标签: java object arraylist


【解决方案1】:

使用原始泛型类型是bad practice。这样你就失去了泛型的所有优势。

也就是说,为了说明您的子列表是否由字符串组成:

        ArrayList<List<String>> SGenresMaster = new ArrayList<List<String>>();
        ArrayList<String> S1Genres = new ArrayList<String>();
        ArrayList<String> S2Genres = new ArrayList<String>();
        ArrayList<String> S3Genres = new ArrayList<String>();

        SGenresMaster.add(S1Genres);
        SGenresMaster.add(S2Genres);  
        SGenresMaster.add(S3Genres);


    SGenresMaster.get(0).get(0); //gets the first element of S1Generes

【讨论】:

  • 非常感谢,我知道有一种非常简单的方法可以做到这一点
  • 在java 7中不应该有 或类似的两边或 表示法。虽然奇怪的是我的编译器似乎很好
  • @RichardTingle 你是对的。但这不是编译错误,尽管大多数编译器会生成警告。为清晰起见已修复。
【解决方案2】:

我希望你的问题是正确的:

for(ArrayList<String> arr: SGenresMaster){
    //arr can be any array from SGenresMaster
    for(String s : arr){
      //do something
   }

}

 SGenresMaster.get(index).get(someOtherIndex);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多