轉貼自
通常Vector裡的都是物件的reference,而不是實際的物件
存放在Vector裡的都是物件,所以才會有String和int...等等的資料型態的差異,
例如:String在JAVA裡事物件的型態,可是int...等等,都是數值,而不是物件
把一些物件塞入Vector, 例如:
Vector v = new Vector();
Vector w = new Vector();
String[] firstnames = { "Spencer" , "Benx" , "Jaseph" , "Isao" , "Sidekick" };
String[] lastnames = { "is handsome boy" , "is our manager" , "is sale's father" , "is
tobacco's man" , "is our MIS"};
for( int i =0 ; i < firstnames.length ; i++ )
v.add(firstnames[i]);
for( int k =0 ; k < lastnames.length ; k++)
w.add(lastnames[k]);
for( int j = 0 ; j < v.size() ; j++)
System.out.println(" Odject.co's the best teammates = " + v.get(j) +" "+ w.get(j));
NEW起來一個Vector,然後跑一個for迴圈,把值塞入.
get出來時候,也是以同樣的方式
或者用Iterator來一一取得集合裡的值
Iterator it = v.iterator();
Iterator lit = w.iterator();
while(it.hasNext()){
System.out.println(" Odject.co's the best teammates(Iterators) = " + it.next()+" "+ lit.next());
}
以上面的結果,出來的值:
Odject.co's the best teammates = Spencer is handsome boy
Odject.co's the best teammates = Benx is our manager
Odject.co's the best teammates = Jaseph is sale's father
Odject.co's the best teammates = Isao is tobacco's man
Odject.co's the best teammates = Sidekick is our MIS
Odject.co's the best teammates(Iterators) = Spencer is handsome boy
Odject.co's the best teammates(Iterators) = Benx is our manager
Odject.co's the best teammates(Iterators) = Jaseph is sale's father
Odject.co's the best teammates(Iterators) = Isao is tobacco's man
Odject.co's the best teammates(Iterators) = Sidekick is our MIS
如果是一個陣列其元素是數值(只有字串是物件,塞入集合中只能塞入物件)時:
Vector a = new Vector();
int[] h = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 };
for( int g = 0 ; g < h.length ; g++ )
a.add( new Integer ( h[g] ));
Iterator lv = a.iterator();
while(lv.hasNext()){
System.out.println( " LV的(iterator) "+ lv.next());
}
雜湊表的用法學習:
//雜湊表的塞值和取值
HashMap aMap = new HashMap();
String myKey1 = "key1";
String myKey2 = "key2";
Integer theObject1 = new Integer(12345);
String theObject2 = "塞入的第二個值 theObject2";
aMap.put( myKey1 , theObject1);
aMap.put( myKey2 , theObject2);
if(aMap.put( myKey1 , theObject1) != null ){
System.out.println(" Oh Ya Baby ~~~~ I put an object to HashMap ");
}
System.out.println(aMap.get(myKey1));
System.out.println(aMap.get("key1"));
System.out.println(aMap.get("key2"));
雜湊表中用Iterator的塞key取值法:
Set keys = aMap.keySet();
Iterator keyIter = keys.iterator();
//Iterator keyIter = aMap.keySet().iterator();
while(keyIter.hasNext()){
System.out.println("aMap.Iterator(value) = " + keyIter.next());
}
沒有留言:
張貼留言