简体   繁体   中英

Accessing data from an Arraylist stored in an Arraylist - Java

I'm trying to access data from an Arraylist that is stored in an Arraylist. I'm sure there is a really easy way to do this and I don't want to waste anyone's time but I've tried lots of ways and can't seem to find the answer anywhere. Any help would be really appreciated.

This is my code for creating the Arrays.

    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);

    }

Basically i need to be able to access any index of S1Genres using SgenresMaster.

So far I've only managed to get the data out as a long string so I thought I'd post my current method for getting the data I need, as i thought it would probably make the pro's here cringe/laugh.

    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;
} 

Using raw generic types is a bad practice . You lose all the advantages of generics that way.

That said, for illustration if your sublists are made up of Strings:

        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

I hope your got your question right:

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

}

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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