Vector ArrayList Hashtable的使用实例

本文展示了一个使用Java集合框架的示例程序,包括Vector、ArrayList及Hashtable等类的使用方式,并介绍了如何进行元素的添加、转换及检索操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.*;

public class Application
{
 public static void main(String[] args)  //三个的声明顺序不能颠倒
 {  
  Vector dogvessel=new Vector();
  ArrayList al1=new ArrayList();
  ArrayList al2=new ArrayList();
  dogvessel.addElement(new dog(1));
  dogvessel.addElement(new dog(9));
  dogvessel.addElement(new dog(8));
  dogvessel.addElement(new dog(2));
  Enumeration e1=dogvessel.elements();//Enumeration是个接口,实质是抽象类,
  if(e1.hasMoreElements())
  ((dog)e1.nextElement()).getdogage();   //第一个元素的Object引用从nextElement()开始
  for(int i=0;i  {
   ((dog)dogvessel.elementAt(i)).getdogage();
  }
  al1.add(Integer.toString(1));
  al1.add(Integer.toString(2));
  al1.add(Integer.toString(3));
  
  al2.add(new Integer(1));
  al2.add(new Integer(2));
  al2.add(new Integer(3));
        // al2.trimToSize()
  //Java里ArrayList没有 getEnumeration,那个估计是其他编程语言的
  String[] array1=(String [])al1.toArray(new String[0]);
  Integer[] array2=(Integer [])al2.toArray(new Integer[0]);
  System.out.println(array1[1]);
  System.out.println(array2[1]);//非基本类型里都包含了已定义好的toString()方法
 }
}

 

import java.util.*;
/**
 * @author nebula
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
class Groundhog {
   int ghNumber;
   Groundhog(int n) { ghNumber = n; }
 }

 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();
    // Enumeration e1=ht.elements();  Hashtable支持Enumeration
     for(int i = 0; i < 10; i++)
       ht.put(new Groundhog(i), new Prediction());//第一个参数作为键,第二个参数作为值 内容
     System.out.println("ht = " + ht + "/n");//这句直接将整个hashtable输出
     System.out.println(
       "Looking up prediction for groundhog #3:");
     Groundhog gh = new Groundhog(3);
     if(ht.containsKey(gh))//这么是不会输出结果的,因为不是内容相同就可以说包含,gh不是Hashtable包含的对象
       System.out.println((Prediction)ht.get(gh));
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值