2011-07-28 79 views
0

我的函数返回一个字符串数组的列表。我如何访问/打印main()中列表中的第一个字符串数组。Java - 使用列表的特定元素

public class URLReader{ 
public List<String[]> functie(String x) throws Exception{ 
... 
List<String[]> substrList = new ArrayList<String[]>(); 
substrList.add(tds2); 
substrList.add(tds3); 
return substrList; 
} 
public static void main(String[] args) throws Exception { 
URLReader s = new URLReader(); 
for (??????????) 

回答

0

正如其他答案已经指出,要使用列表中的第一个元素,您可以调用List.get(int)方法。

someList.get(0); 

在你的代码,以遍历在第一列表索引的字符串数组,你会想要的东西,看起来像:

for(String str : s.functie(arg).get(0)) { 
    //Do something with the string such as... 
    System.out.println(str); 
} 
2

如果你想遍历所有阵列(你开始你的问题写:

for (String[] array : s.functie("...")) { 
    ... 
} 

如果你只想要第一个:

String[] array = array.get(0); 
+0

“functie”使用字符串参数。我称之为函数s.functie(x);其中x是一个网址 –

+0

@Bogdan S:好的,然后使用它与一个URL! :) – dacwe

+0

我的函数获取一个url作为参数,并返回一个两个字符串数组的列表(第一个包含一个字符串数组的链接,第二个字符串数组的描述)。在main()中,我只需要访问列表的第一个元素并打印它。你能否更具体一些?谢谢 –

0

你可以得到像这样的列表中的第一个元素:

final List<String[]> arrayList = new ArrayList<String[]>(); 
arrayList.get(0); // get first element 

或者你可以使用一个队列,这个队列内置了这些任务的方法。

final Queue<String[]> linkedList = new LinkedList<String[]>(); 
linkedList.poll(); // get (and remove) first element 
linkedList.peek(); // get (but do not remove) first element 
相关问题