public static <T> void print(Collection<T> l)
如果我有一个包含 a、b 和 c 的集合,我希望输出为
[a,b,c]
如果它是空的,我希望它是
[]
现在是我的代码。
public class CollectionOps {
public static <E, T extends Iterable<E>> void print(T a){
//for(Iterable type Iterable element : collection)
for (E x : a) {
System.out.print(x);
}
}
public static void main(String[] args){
ArrayList<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
print(a);
}
}
输出:abc
也许我可以以某种方式使用 System.out.printf() ?
最佳答案
集合类通常会重写toString
以准确生成该输出。因此,如果您有一个Collection
,您可以这样做
System.out.println(collection);
这是有效的,因为 println
调用 toString
。
如果您想以这种形式打印 Iterable
,我只需将其设为集合即可。
List<Object> list = new ArrayList<>();
for (Object o : iterable)
list.add(o);
System.out.println(list);
另请注意,您可以使用通配符改进方法签名。
public static void print(Iterable<?> iterable)
关于java - 打印对象集合中的元素的通用类方法 "print",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36515510/