JavaAPI总结

本文介绍了Java编程中数据类型的应用、集合类的使用、日期时间处理、内存管理及异常处理等方面的知识,涵盖从基本概念到高级应用的全面介绍。

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

n  数据类型

编程举例:在屏幕上打印一个星号(*)组成矩形,矩形的宽度和高度通过启动程序时传递给main方法的参数指定:

 

publicclass TestType

{

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              int height = new Integer(args[0]);

              int wight = Integer.parseInt(args[1]);

              //int wight1 =Integer.valueOf(args[1]).intValue();

             

              for(int i=0;i<height;i++)

              {

                     StringBuffer sb = new StringBuffer();

                     for(int j=0;j<wight;j++)

                     {

//* 参数的字符表示形式追加到此序列

                            sb.append('*');

                     }

                     System.out.println(sb.toString());

              }

             

 

       }

 

}

 

n  集合类

集合类用于存储组对象,其中每个对象称之为元素;经常用到的vectorEnumerationArrayListCollectioniteratorsetList等集合类和接口;

l  Vector类与Enumeration接口

Vector 类是java提供的一种高级数据结构,可以用于保存一系列的数据对象,vector提供了一组与动态数组相近的功能;

Vector所有的线程方法都是同步,当有两个线程并发去访问vector对象时,线程是安全,不需要考虑线程同步的问题,是安全的;即使只有一个线程去访问vector对象时,仍然存在同步监视器检查的情况,这就需要额外的开销,程序执行的效率将会降低。

编程举例:将键盘上输入的一系列数字序列中每个数字存储到vector对象中,然后在屏幕打印每位数字相加的结果:例如:输入1234打印出10

package com.huawei.api.vector;

 

import java.util.Enumeration;

import java.util.Vector;

 

publicclass TestVctor {

 

       /**

        * @param<E>

        * @param args

        */

       publicstatic void main(String[] args)

       {

              Vector v = new Vector();

              int b=0;

              int sum=0;

              System.out.println("Please put into number:");

              while(true)

              {

                     try

                     {

                          b = System.in.read();

                     }

                     catch(Exception ex)

                     {

                            ex.printStackTrace();

                     }

                     if(b=='\r' || b=='\n' )

                     {

                            break;

                     }

                     else

                     {

                            int nmb = b-'0';

                           

                            //将指定的组件添加到此向量的末尾,将其大小增加 1

                            v.addElement(new Integer(nmb));

                     }

              }

             

              //返回此向量的组件的枚举。

              Enumeration ve =v.elements();

             

              //测试此枚举是否包含更多的元素。

              while(ve.hasMoreElements())

              {

                     // 如果此枚举对象至少还有一个可提供的元素,则返回此枚举的下一个元素。

                     Integer intObj =(Integer)ve.nextElement();

                     sum += intObj.intValue();

              }

              System.out.print(sum);

 

       }

 

}

l  Collection 接口和 Iterator接口

功能和Vector类与Enumeration接口类似

注:ArrayList所有方法是不同步,如果不存在多线程安全问题使用ArrayList要比使用Vector效率高,但是如果存在多线程问题使用ArrayList就应该考虑线程同步问题;

编程举例:用ArrayListIterator改写上面的例子程序

 

package com.huawei.api.collection;

 

import java.util.ArrayList;

import java.util.Iterator;

 

publicclass TestCollection {

 

       /**

        * @param<E>

        * @param args

        */

       publicstatic void main(String[] args)

       {

              ArrayList ar = new ArrayList();

              int b=0;

              int sum=0;

              System.out.println("Please put into number:");

              while(true)

              {

                     try

                     {

                          b = System.in.read();

                     }

                     catch(Exception ex)

                     {

                            ex.printStackTrace();

                     }

                     if(b=='\r' || b=='\n' )

                     {

                            break;

                     }

                     else

                     {

                            int nmb = b-'0';

                            //将指定的组件添加到此向量的末尾,将其大小增加 1

                            ar.add(new Integer(nmb));

                     }

              }

             

              //返回在此 collection 的元素上进行迭代的迭代器。

              Iterator ve =ar.iterator();

             

              //如果仍有元素可以迭代,则返回 true

              while(ve.hasNext())

              {

                     // 返回迭代的下一个元素

                     Integer intObj =(Integer)ve.next();

                     sum += intObj.intValue();

              }

              System.out.print(sum);

 

       }

 

}

 

 

 

 

l  Collectionsetlist区别如下:

Collection 各元素对象之间没有指定顺序,允许有重复元素和多个null元素对象;

Set各元素对象之间没有指定顺序,不允许重复元素和最多只允许一个null元素对象;

List 各元素对象之间有指定顺序,允许重复元素和多个null元素对象;

编程举例:(按照list的指定顺序排序)

package com.hudewei.api.list;

 

import java.util.ArrayList;

import java.util.Collections;

 

publicclass TestList {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              ArrayList al = new ArrayList();

              al.add(new Integer(1));

              al.add(new Integer(3));

              al.add(new Integer(2));

              System.out.println(al.toString());

             

              //根据元素的自然顺序对指定列表按升序进行排序。

              Collections.sort(al);

              System.out.println(al.toString());

 

       }

 

}

 

注:collections类所有的成员方法都是静态的,主要用于操作集合类对象,但是collections本身不是集合类对象,只是提供了各种方法去操作集合类对象;

 

 

 

 

 

 

n  HashTable

HashTable不仅可以像Vector一样动态的存储系列对象,而且对存储的每一个对象(称为值)都会安排另一个对象(称为关键字)与之相关联;

用作关键字的类必须覆盖object.hashcode()方法和object.equals()方法;

编程举例:使用自定义类作为hashtable关键字类;

package com.hudewei.api.hashtable;

 

import java.util.Enumeration;

import java.util.Hashtable;

 

publicclass TestHashTable {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Hashtable<MyKey, Integer>hashTa = new Hashtable<MyKey, Integer>();

             

              hashTa.put(new MyKey("wangwu",25), new Integer(1));

              hashTa.put(new MyKey("zhangsan",23), new Integer(2));

              hashTa.put(new MyKey("lisi",24), new Integer(3));

              hashTa.put(new MyKey("王五",35), new Integer(4));

             

              Enumeration<MyKey> hashE =hashTa.keys();

             

              while (hashE.hasMoreElements())

              {

                     MyKey key =(MyKey)hashE.nextElement();

                    

                     System.out.print(key+: ");

                     System.out.println(hashTa.get(key));

              }

 

       }

 

}

 

 

 

n  Properties

PropertiesHashtable的子类

增加了将Hashtable对象中的关键字和值保存到文件中和从文件中读取关键字和值到Hashtable对象中的方法;

如果要用properties.store()方法存储properties对象中的内容,则每个属性的关键字和值都必须是String类型;

编程举例:使用properties把程序启动运行的次数记录在某个文件中,每次运行时打印出运行的次数。

package com.huawei.api.properties;

 

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.Properties;

 

publicclass TestProperties {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Properties proFil = new Properties();

              try

              {

                     //从输入流中读取属性列表(键和元素对)。

                     proFil.load(new FileInputStream("COUNT.txt"));

              }

              catch (Exception e)

              {

                     //调用 Hashtable 的方法 put

                     proFil.setProperty("count", String.valueOf(0));

              }

             

              int c = Integer.parseInt(proFil.getProperty("count")) + 1;

              System.out.println("只是第"+ c +"次运行程序");

              proFil.setProperty("count", String.valueOf(c));

              try

              {

                     //以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,

                     //将此 Properties 表中的属性列表(键和元素对)写入输出流。

                     proFil.store(new FileOutputStream("COUNT.txt"),"Program is used");

              }

              catch (Exception e)

              {

                     e.printStackTrace();

              }

             

       }

 

}

n  System Runtime

l  System

Exit方法;

CurrentTimeMillis方法;

Java虚拟机系统属性;

GetPropertiesSetproperties方法;

编程举例:获取系统参数;

package com.hudewei.api.system;

 

import java.util.Enumeration;

import java.util.Properties;

 

publicclass TestSystem {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              // TODO Auto-generated method stub

              Properties sp = System.getProperties();

              Enumeration e =sp.propertyNames();

              while(e.hasMoreElements())

              {

                     String key =(String)e.nextElement();

                     System.out.println(key+" = "+sp.getProperty(key));

                    

              }

       }

 

}

l  Runtime

Runtime类封装了java虚拟机线程,一个java虚拟机对应一个runtime实例对象,runtime中许多方法与system中的许多方法重复,不能直接创建runtime实例对象,也就是不能通过new创建实例对象,通过Runtime.getRuntime获取实例对象的应用;由于java虚拟机本身就是windows操作上的一个进程,在这种进程可以启动其他windows进程中的实例,通过这种方式启动其他的线程就是子线程;

编程举例:在java程序中启动一个windows记事本中进程实例,在该程序运行实例中打开java源文件,启动记事本程序5秒中被自动关闭;

package com.hudewei.api.runtime;

 

publicclass TestRuntime {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Process pr = null;

              try

              {

                     pr = Runtime.getRuntime().exec("notepad.exe  E:/testAPITestRuntime.java");

                     Thread.sleep(5000);

                     pr.destroy();

              }

              catch(Exception ex)

              {

                     ex.printStackTrace();

              }

             

             

 

       }

 

}

 

n  与日期和时间有关的类

常用的几个类:DateDateFormat Calendar

l  Calendar类:当做日期字段之间的相互操作,就是年,月,日,小时,分,秒等局部字段信息;

Calender.add方法根据日历的规则,为给定的日历字段添加或减去指定的时间量;

Calendar.get方法返回给定日历字段的值;

Calendar.set方法将给定的日历字段设置为给定值;

Calendar.getInstance静态方法,Calendar是一个抽象类,需要通过getInstance方法获取一个Calendar类型

编程举例:计算出当前日期时间315天后的日期时间,并用“xxxxxxxxxxxx秒”的格式输出;

package com.hudewei.api.calendar;

 

import java.util.Calendar;

 

publicclass TestCalendar {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              // TODO Auto-generated method stub

              Calendar cal = Calendar.getInstance();

              System.out.println(cal.get(Calendar.YEAR)+""+cal.get(Calendar.MONTH)+""+cal.get(Calendar.DAY_OF_MONTH)+""+cal.get(Calendar.HOUR_OF_DAY)+

                       ":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":"+cal.get(Calendar.MILLISECOND));

              cal.add(Calendar.DAY_OF_YEAR, 315);

              System.out.println(cal.get(Calendar.YEAR)+""+cal.get(Calendar.MONTH)+""+cal.get(Calendar.DAY_OF_MONTH)+""+cal.get(Calendar.HOUR_OF_DAY)+

                       ":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND)+":"+cal.get(Calendar.MILLISECOND));

 

       }

 

}

 

l  Date

Java.text.DateFormatjava.text.SimpleDateFormat子类

DateFormat类可以将Date实例对象中的日期按照某种特定格式进行输出,或者将某一种特定格式的日期字符串转换成实力对象;

SimpleDateFormat子类用于把Date对象中的日期格式化为本地字符串,或经过语义分析把时间日期字符串转化为实例对象;

编程举例:将“2013-6-11”格式的日期字符串转换成“2013611日”的格式;

package com.hudewei.api.date;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

publicclass TestDateFormate {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Date date = new Date();

              //定义日期输出的格式

          SimpleDateFormat DateFomat1 = new SimpleDateFormat("yyyy-MM-dd");

          SimpleDateFormat DateFomat2 = new SimpleDateFormat("yyyyMMdd");

          SimpleDateFormat DateFomat3 = new SimpleDateFormat("MM/dd/yyyy");

          try

          {

                      date = DateFomat1.parse("2013-12-01");

              } catch (ParseException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

              System.out.println(DateFomat1.format(date));

              System.out.println(DateFomat2.format(date));

              System.out.println(DateFomat3.format(date));

       }

 

}

举例演变:将当前日期对象分别按照“yyyy-MM-dd,”yyyyMMdd或者“MM/dd/yyyy”格式输出:

package com.hudewei.api.date;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

publicclass TestDateFormate {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Date date = new Date();

              //定义日期输出的格式

          SimpleDateFormat DateFomat1 = new SimpleDateFormat("yyyy-MM-dd");

          SimpleDateFormat DateFomat2 = new SimpleDateFormat("yyyyMMdd");

          SimpleDateFormat DateFomat3 = new SimpleDateFormat("MM/dd/yyyy");

          /*try

          {

                      date =DateFomat1.parse("2013-12-01");

              } catch (ParseException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }*/

              System.out.println(DateFomat1.format(date));

              System.out.println(DateFomat2.format(date));

              System.out.println(DateFomat3.format(date));

       }

 

}

n  TimerTimerTask

Schedule方法主要有如下几种重载形式:

schedule(TimerTasktask, Datetime)安排在指定的时间执行指定的任务。

schedule(TimerTasktask, DatefirstTime, long period)安排指定的任务在指定的时间开始进行重复的固定延迟执行

schedule(TimerTasktask, long delay)安排在指定延迟后执行指定的任务。

schedule(TimerTasktask, long delay, long period)安排指定的任务从指定的延迟后开始进行重复的固定延迟执行

TimerTask类实现了Runnable接口,要执行的方法有他里面的Run()来之完成;

编程举例:程序启动三十秒后,自动启动windows自带的计算器程序:

package com.hudewei.api.timer;

 

import java.io.IOException;

import java.util.Timer;

import java.util.TimerTask;

 

publicclass MyTimerTask extends TimerTask

{

       Timer timer = new Timer();

       public MyTimerTask(Timer timer)

       {

              this.timer = timer;

       }

       @Override

       publicvoid run()

       {

              try

              {

                     Runtime.getRuntime().exec("calc.exe");

              }

              catch (IOException e)

              {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

              timer.cancel();

       }

 

}

package com.hudewei.api.timer;

 

import java.util.Timer;

 

publicclass TestTimer {

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              Timer timer = new Timer();

              MyTimerTask myTimerTask = new MyTimerTask(timer);

              timer.schedule(myTimerTask,30000);

       }

 

}

 

举例演变:程序启动在指定时间启动后每相隔30秒输出一次当前的系统时间;

package com.hudewei.api.timer;

 

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Timer;

import java.util.TimerTask;

 

public class MyTestTimerTask extends TimerTask

{

   Timer timer =new Timer();

         publicMyTestTimerTask(Timer timer)

         {

                    this.timer = timer;

         }

 

         @Override

         public void run()

         {

                   Date date =new Date();

                   SimpleDateFormatdateFormat= new SimpleDateFormat("yyyy/MM/dd,HH:mm:ss");

                   System.out.println(dateFormat.format(date));

         }

}

 

package com.hudewei.api.timer;

 

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Timer;

 

publicclass MyTestTimer {

 

       privatestatic Date date;

 

       /**

        * @param args

        */

       publicstaticvoid main(String[] args)

       {

              date = new Date();

              Timer timer = new Timer();

              MyTestTimerTask myTestTimer = new MyTestTimerTask(timer);

         SimpleDateFormat dateFormate= new SimpleDateFormat("yyyy-MM-dd,HH:mm:ss");

              try

              {

                     date = dateFormate.parse("2013-6-11,2:18:10");

              }

              catch (ParseException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

             

              timer.schedule(myTestTimer, date, 3000);

 

       }

 

}

 

n  Math Random

l  Math类包含了所有用于几何和三角运算的方法;

l  Random是一个伪随机数产生器;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值