[英]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. 我正在尝试从存储在Arraylist中的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. 基本上,我需要能够使用SgenresMaster访问S1Genres的任何索引。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.