1,学了许多理伦,发现最好的解决办法还是多敲代码!
例1,向ArrayList中插入一个数据:
import java.util.ArrayList;
public class AddExample {
public static void main(String[] args) {
ArrayList<String> alist=new ArrayList<String>();
alist.add("2");
alist.add("7");
alist.add("9");
alist.add(1,"4");
for(String s:alist)
System.out.println(s);
}
}
Output:
2
INSERTED
7
9
例2:ArrayList的简单操作:
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList al=new ArrayList();
System.out.println("al的大小:"+al.size());
//向arrayList中添加元素
al.add("C");
al.add("S");
al.add("A");
al.add("F");
al.add("B");
al.add("D");
al.add(1,"A2");
System.out.println("添加后的大小:"+al.size());
//显示所有的arrayList
System.out.println("显示al:"+al);
//从中移除一个元素
al.remove("F");
al.remove(2);
System.out.println("移除后的大小:"+al.size());
System.out.println("显示移除部分元素后的al:"+al);
}
}
output:
al的大小:0
添加后的大小:7
显示al:[C, A2, S, A, F, B, D]
移除后的大小:5
显示移除部分元素后的al:[C, A2, A, B, D]
例3:简单操作List, Set, SortedSet, LinkedHashSet, Map, LinkedHashMap
import java.util.*;
public class CollectionExample {
public static void main(String[] args) {
List l=new LinkedList();
l.add("List:angel");
l.add("schildt");
l.add("mathew");
l.add("schildt");
print(l);
Set s=new HashSet();
s.add("Set:rose");
s.add("schildt");
s.add("mathew");
s.add("schildt");
print(s);
SortedSet ss=new TreeSet();
ss.add("Set:jasmine");
ss.add("schildt");
ss.add("mathew");
ss.add("schildt");
print(ss);
LinkedHashSet sss=new LinkedHashSet();
sss.add("set:winslet");
sss.add("schildt");
sss.add("mathew");
sss.add("schildt");
print(sss);
Map<String,String> m1=new HashMap<String,String>();
m1.put("map", "map:HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());
SortedMap<String,String> sm=new TreeMap<String,String>();
sm.put("map", "treeMap:treeMap");
sm.put("schildt", "java2");
sm.put("mathew", "hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());
LinkedHashMap<String,String> lm=new LinkedHashMap<String,String>();
lm.put("map", "LinkedHashMap:LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());
}
/**
* @param l
*/
private static void print(Collection coll) {
Iterator iter=coll.iterator();
while(iter.hasNext())
{
String elem=(String)iter.next();
System.out.print(elem+" ");
}
System.out.println(" ");
}
}
Output:
schildt Set:rose mathew
Set:jasmine mathew schildt
set:winslet schildt mathew
schildt mathew map
java2s hyden map:HashMap
map mathew schildt
treeMap:treeMap hyden java2s
map schildt mathew
LinkedHashMap:LinkedHashMap java2s hyden