1 public static void main(String args[]) { 2 List ints = Arrays.asList(new Integer[]{new Integer(1), new Integer(3)}); 3 int s =0; 4 for(Iterator it = ints.iterator(); it.hasNext();) 5 { 6 int n = ((Integer)it.next()).intValue(); 7 s+=n; 8 } 9 System.out.println(s); 10 }
public static void main(String args[]) { List<Integer> ints = Arrays.asList(1,2,3); int s = 0; for(int n: ints) { s+=n; } System.out.println(s); }
public static void main(String args[]) { List<String> words = new ArrayList<String>(); words.add("Hello"); words.add("world"); String s = words.get(0) +words.get(1); System.out.println(s); }
package cn.galc.test; import java.util.*; class Lists{ public static <T> List<T> toList(T[] arr) { List<T> list = new ArrayList<T>(); for (T t: arr) { list.add(t); } return list; } } public class Test { public static void main(String args[]) { List<String> words = Lists.toList(new String[]{"sun","ming"}); for(String s:words) System.out.println(s); } }
本文展示了几种在Java中操作集合的方法,包括使用不同方式遍历List并进行累加计算,以及将数组转换为List的示例。通过具体代码演示了如何利用for-each循环简化List遍历过程,同时介绍了自定义类Lists实现数组到List的转换。

218

被折叠的 条评论
为什么被折叠?



