当前位置: 代码迷 >> Java相关 >> Collection中的小问题
  详细解决方案

Collection中的小问题

热度:273   发布时间:2007-07-07 15:20:26.0
Collection中的小问题

import java.util.*;

public class Collection1 {
public static Collection
fill(Collection c, int start, int size) {
for(int i = start; i < start + size; i++)
c.add(Integer.toString(i));
return c;
}
public static Collection
fill(Collection c, int size) {
return fill(c, 0, size);
}
public static Collection fill(Collection c) {
return fill(c, 0, 10);
}
public static Collection newCollection() {
return fill(new ArrayList());
}
public static Collection
newCollection(int start, int size) {
return fill(new ArrayList(), start, size);
}
public static void print(Collection c) {
for(Iterator x = c.iterator(); x.hasNext();)
System.out.print(x.next() + " ");
System.out.println();
}
public static void main(String[] args) {
Collection c = newCollection();
c.add("ten");
c.add("eleven");
print(c);
Object[] array = c.toArray();
// Make a String array from the List:
String[] str =
(String[])c.toArray(new String[1]);
// Find max and min elements; this means
// different things depending on the way
// the Comparable interface is implemented:
System.out.println("Collections.max(c) = " + //我想问下,这里为什么是ten?
Collections.max(c));

System.out.println("Collections.min(c) = " +
Collections.min(c));
// Add a Collection to another Collection
c.addAll(newCollection());
print(c);
c.remove("3"); // Removes the first one
print(c);
c.remove("3"); // Removes the second one
print(c);
// Remove all components that are in the
// argument collection:
c.removeAll(newCollection());
print(c);
c.addAll(newCollection());
print(c);
// Is an element in this Collection?
System.out.println(
"c.contains(\"4\") = " + c.contains("4"));
// Is a Collection in this Collection?
System.out.println(
"c.containsAll(newCollection()) = " +
c.containsAll(newCollection()));
Collection c2 = newCollection(5, 3);
// Keep all the elements that are in both
// c and c2 (an intersection of sets):
c.retainAll(c2);
print(c);
// Throw away all the elements in c that
// also appear in c2:
c.removeAll(c2);
System.out.println("c.isEmpty() = " +
c.isEmpty());
c = newCollection();
print(c);
c.clear(); // Remove all elements
System.out.println("after c.clear():");
print(c);
}
}

搜索更多相关的解决方案: Collection  

----------------解决方案--------------------------------------------------------
ten 和eleven
t比e大
----------------解决方案--------------------------------------------------------
楼上正解
----------------解决方案--------------------------------------------------------

谢谢``````努力`````


----------------解决方案--------------------------------------------------------
  相关解决方案