一、stack(后入先出的集合,stack从vector继承而来,拥有vector所有方法)
import java.util.Stack;
public class Stacks{
static String[] months = {
"January", "February", "March", "April", "May",
"June", "July", "August", "September", "October",
"November", "Docembetr"
};
public static void main(String[] args) {
Stack stk = new Stack();
for(int i=0; i<months.length; i++){
stk.push(months[i] + "");
}
System.out.println("stk = " + stk);
stk.addElement("This is last line");
System.out.println("element 5 = " + stk.elementAt(5));
System.out.println("poping elements:");
while(!stk.empty()){
System.out.println(stk.pop());
}
}
}
结果:
stk = [January, February, March, April, May, June, July, August, September, October, November, Docembetr]
element 5 = June
poping elements:
This is last line
Docembetr
November
October
September
August
July
June
May
April
March
February
January
二、HashTable
1、实现随机数记数,Math.random()范围[0,1);
import java.util.Hashtable;
class Counter{
int i = 1;
public String toString(){
return Integer.toString(i);
}
}
public class Statistics{
public static void main(String[] args) {
Hashtable ht = new Hashtable();
for(int i=0; i<10000; i++){
Integer r = new Integer((int)(Math.random()*20));
if(ht.containsKey(r)){
((Counter)ht.get(r)).i ++;
}else{
ht.put(r, new Counter());
}
}
System.out.println(ht);
}
}
结果:
{19=518, 18=486, 17=547, 16=489, 15=470, 14=508, 13=486, 12=508, 11=486, 10=527, 9=493, 8=535, 7=464, 6=492, 5=489, 4=483, 3=519, 2=483, 1=483, 0=534}
2、创建“关键”类(Groundhog是从通用的Object根类继承的,事实上是用Object的hashCode()方法生成每个对象的散列码,而且默认情况下只使用它的对象地址,当HashTable试图判断我们的键是否等于表内的某个键时,就会用到这个方法,同样的,默认的Object.equals()只是简单地比较对象地址,所以为了在HashTable中将自己的类作为键使用,必须同时覆盖hashCode()和equals()。)
import java.util.Hashtable;
class Groundhog{
int ghNumber;
Groundhog(int n){
ghNumber = n;
}
public int hashCode(){
return ghNumber;
}
public boolean equals(Object o){
return (o instanceof Groundhog)
&& (ghNumber == ((Groundhog)o).ghNumber);
}
public String toString(){
return String.valueOf(ghNumber);
}
}
class Prediction{
boolean shadow = Math.random() > 0.5;
public String toString(){
if(shadow){
return "Six more weeks of Winter!";
}else{
return "Early Spring!";
}
}
}
public class SpringDetector{
public static void main(String[] args) {
Hashtable ht = new Hashtable();
for(int i=0; i<10; i++){
ht.put(new Groundhog(i), new Prediction());
}
System.out.println("ht = " + ht);
System.out.println("Looking up :");
Groundhog gh = new Groundhog(3);
if(ht.containsKey(gh)){
System.out.println((Prediction)ht.get(gh));
}
}
}
结果:
ht = {9=Early Spring!, 8=Six more weeks of Winter!, 7=Early Spring!, 6=Early Spring!, 5=Early Spring!, 4=Early Spring!, 3=Six more weeks of Winter!, 2=Six more weeks of Winter!, 1=Six more weeks of Winter!, 0=Six more weeks of Winter!}
Looking up :
Six more weeks of Winter!