我想更好地學習java,並且我得到了一個問題。java函數 - 打印(集合c)?
說我有兩個集合,一個ArrayList和一個LinkedHashSet。是否有可能作出這樣的函數:
void print(collection c) {
for (object tmp:c) {
System.out.println(tmp);
}
}
我想更好地學習java,並且我得到了一個問題。java函數 - 打印(集合c)?
說我有兩個集合,一個ArrayList和一個LinkedHashSet。是否有可能作出這樣的函數:
void print(collection c) {
for (object tmp:c) {
System.out.println(tmp);
}
}
使用大寫字母:
private void printCollection(Collection collection) {
for (Object obj : collection) {
System.out.println(obj);
}
}
應該是'for(Object obj:c)' – 2010-01-05 17:38:21
秒已經太晚了。應該是'Collection >','element'或'e'而不是'obj'。 – 2010-01-05 17:40:13
確保您實現了toString()方法 – Brendan 2010-01-05 18:22:20
是。 ArrayList和LinkedHashSet都是集合。你寫的方法接受一個Collection(注意大寫C),所以它會接受任何類型的集合。這被稱爲多態。
基本上你只需要使用催產素的迭代器:
void print(collection c)
{
for (object tmp:c.iterator())
{
System.out.println(tmp);
}
}
在Java中,迭代器不可迭代。你只能在迭代器中使用for-each,而不能迭代器。 – 2010-01-05 17:43:28
ack,是。但誰是誰決定呢? :) – 2010-01-05 19:22:23
這是可能的,因爲這兩種類型的實施Collection<E>
。約定是用於Java中的類類型以大寫字母開頭。從1.5開始,Java已經使用generics作爲它的集合,並且您應該在所有新代碼中使用它們。由於您使用的是1.5樣式for
循環,因此您應該編寫通用代碼。
通常情況下,儘可能使函數在最小特定類型上運行會更好,因爲這可以實現最大範圍的重用。在這種情況下,你只需要從Collection<T>
到Iterable<T>
之間的任何一個,因爲你只需要一些可以與for循環一起工作的東西。因此,結合泛型和最小功率給出:
public class PrintLinePrinter {
public <T> void print (Iterable<T> collection) {
for (T item : collection) {
System.out.println(item);
}
}
}
'T'是不必要的。只需做'public void print(Iterable > collection)'並將'T item'改爲'Object item' – user102008 2011-08-31 04:01:11
System.out.println(Collection c)已經以可讀格式打印任何類型的集合。 但是,如果集合包含用戶定義的對象,則需要在用戶定義的類中實現toString()。
'環路免費' 的解決方案:
void print(collection c) {
System.out.println(Arrays.toString(c.toArray())); }
只是利用徵收對象,然後就大功告成了。 – 2010-01-05 18:50:05