简体   繁体   中英

ArrayList: Getting a String element within an String element?

I have an ArrayList here that contains X number of String elements that also contain their own X number of String elements. As such:

[ [ c, in,  h,  i, t , n , at, Th,  t, th, ha, e , he, ca],
  [ c, t ,  m, sa,  o, n , at,  s, Th,  t, th, ma, e , he, ca, on], 
  [ a,  b, in,  i, bl, gs, s , an, et, n , la, Pi, ke, nk, ig, a ] ]

I need to get a specific element within the element. eg List at [0][0] would be c , [0][1] would be in and etc... List.get() doesn't appear to be working for me. I'm not sure what is the correct way to do that. I saw in another example using List.get(0)[0] but its not working for me.

Eclipse is saying "The type of the expression must be an array type but it resolved to String" when I try List.get(0)[0] . So I tried List.toArray() which didn't help.

EDIT

HashSet<String> shingleTrimSet = new HashSet<String>();
ArrayList<String> shingleArrayList = new ArrayList<String>();

System.out.println("\nSorted Shingles:");

for(int i = 0; i < lineCount; i++){
    shingleTrimSet.clear();

    for(int idx = 0, jdx = 1; idx+1 < lines[i].length(); idx++, jdx++){
        shingleTrimSet.add( lines[i].substring( idx, jdx+1 ) );
    }
    shingleArrayList.add(i, shingleTrimSet.toString() );

}
System.out.println( shingleArrayList.get(0).get(0) );

Right now I'm just trying to get a specific element in the print line. I'm planning to write a for loop that will look for matching substrings from one element to another. I'm doing Jaccard Similarity.

如果你的意思是你有一个字符串List<List<String>> test那么test.get(0).get(0)将返回第一个子列表中的第一个字符串。

From what you've said, it sounds like you want to split your strings. Given an initialized variable strings declared as:

ArrayList<String> strings;

the following code will likely suit your needs:

for (String s: strings) {
    String[] parts = s.split(",");
    String part2 = parts[1].trim(); // "in" for your first row
}

Or maybe you wanted to gather the split fields into a list of string arrays:

ArrayList<String[]> rows = new ArrayList<String[]>();
for (String s: strings) {
    String[] fields = s.split(",");
    for (int i = 0; i < fields.length; i++)
        fields[i] = fields[i].trim();
    rows.add(fields);
}

which you can now access as you originally intended:

String row1field2 = rows.get(0)[1]; // "in"

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