黑马程序员 API

---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------

API(application programming interface)

Windows API 操作系统提供的各种函数
Java API 提供各种类

String类和StringBuffer类位于Java.lang包中。
String类对象一旦初始不能改变
StringBuffer类可改变字符串

用ToString方法转化成String类

例如:String x = "a"+4+"c",编译时等效于
String x = new StringBuffer().append("a").append(4).append("c")

Windows把“回车键”当作'/r'+'/n',Unix中当作'/n'。

键盘输入字符 当输入“bye”时结束
package com.edu.swu;

import java.io.IOException;

public class ReadLine {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  byte[] buf = new byte[1024];
  String strInfo = null;
  int pos = 0;
  int ch = 0;
  
  while(true){
   ch = System.in.read();
   switch(ch){
   
   case'/r':
    break;
   case'/n':
    strInfo = new String(buf,0,pos);
    if(strInfo == "bye"){
     return;
    }
    else{
     System.out.println(strInfo);
     pos = 0;
     break;
    }
    default:
     buf[pos++] = (byte)ch;
   }
  }
 }

}


打印"*"矩形的例子
package com.edu.swu;

//  main()中的参数在运行时设置
public class TestInteger {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  int w = new Integer(args[0]).intValue();
  int h = Integer.parseInt(args[1]);
  //int h = Integer.valueOf(args[1]).intValue();
  for(int i=0;i<h;i++){
   StringBuffer sb = new StringBuffer();
   for(int j=0; j<w; j++){
    sb.append('*');
   }
   System.out.println(sb.toString());
  }
  
 }

}


后者比前者效率高
String sb = new String();
for(int j=0;j<w;j++){
 sb= sb + '*'//每执行一次产生一个对象
}

StringBuffer sb = new StringBuffer();
for(int j=0; j<w; j++){
 sb.append('*'); //只有一个sb对象
}

集合类
Vector类 Enumeration接口
若奖若干对象存储又不确定其大小可用Vector类

例子:输入数字存储与Vector对象中求和

package com.edu.swu;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Vector;

public class TestVector {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  Vector v = new Vector();
  System.out.println("please enter number");
  while(true)
  {
   int b = System.in.read();
   if(b == '/r' || b == '/n')
    break;
   else
   {
    int num = b - '0';
    v.addElement(new Integer(num));
   }
  }
  int sum = 0;
  Enumeration e = v.elements();
  while(e.hasMoreElements()){
   Integer intObj = (Integer)e.nextElement();
   sum += intObj.intValue();
  }
  System.out.println(sum);
 }

}

Collection接口与Iterator接口

package com.edu.swu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;

public class TestCollection {

 /**
  * @param args
  * @throws IOException
  */
 public static void main(String[] args) throws IOException {
  // TODO Auto-generated method stub
  ArrayList v = new ArrayList();
  System.out.println("please enter number");
  while(true)
  {
   int b = System.in.read();
   if(b == '/r' || b == '/n')
    break;
   else
   {
    int num = b - '0';
    v.add(new Integer(num));
   }
  }
  int sum = 0;
  Iterator e = v.iterator();
  while(e.hasNext()){
   Integer intObj = (Integer)e.next();
   sum += intObj.intValue();
  }
  System.out.println(sum);
 }

}

Vector与ArrayList很类似,
区别:Vector中所有方法线程同步,若用两个线程并发访问Vector对象是安全的,即使只有一个线程,同样需要同步监视器访问,需要额外开销。
ArrayList线程访问不同步,没有并发访问效率比Vector高,若存在多线程则需要程序员自己解决安全通信问题,使用Vector则不需要。

Collection,Set, List的区别:Collection是Set和List的父类,
Collection元素对象无序,可重复,最多与许有一个Null。
Set集合对象无序,不可重复,最多允许一个Null。
List集合元素间有序,允许重复,多个Null。

例子:Sort

package com.edu.swu;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class TestSort {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  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());
  
  
 }

}

Hashtable类

Hashtable不仅可以向Vector一样动态存储一系列对象,而且对存储的每一个对象(称为值)有另一对象(称为关键字)与之相关联关键字和值不能为null,不能有重复的关键字。

Hashtable numbers = new Hashtable();
numbers.put("one",new Integer(1));
numbers.put("two",new Integer(2));
numbers.put("three",new Integer(3));

Integer n = (Interger)numbers.get("two"); 获得关键字关联的值。

用作关键字的类必须覆盖Object.hashCode方法和Object.equals方法。

package com.edu.swu;

public class MyKey {
 public MyKey(String name, int age) {
  // TODO Auto-generated constructor stub
  this.name = name;
  this.age = age;
 }
 public boolean equals(Object obj){
  if(obj instanceof MyKey)
  {
   MyKey objTemp = (MyKey)obj;
   if(name.equals(objTemp.name) && age == objTemp.age)
   {
    return true;
   }
   else
   {
    return false;
   }
  }
  else
  {
   return false;
  }
 }
 
 public String toString(){
  return name + "," + age;
 }
 
 public int hashCode(){
  return name.hashCode() + age;
 }
 private String name = null;
 private int age = 0;
}

package com.edu.swu;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashTableTest {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Hashtable numbers = new Hashtable();
  numbers.put(new MyKey("zhangsan",18), new Integer(1));
  numbers.put(new MyKey("lisi",15), new Integer(2));
  numbers.put(new MyKey("wangwu",19), new Integer(3));
  
  Enumeration e = numbers.keys();
  while(e.hasMoreElements())
  {
   MyKey key = (MyKey) e.nextElement();
   System.out.print(key + "=");
   System.out.println(numbers.get(key));
  }
 }

}

Properties类
Properties类是HashCode的子类,增加了将Hashtable对象中关键字和值保存到文件和从文件中读取关键字和值到HashTable对象中的方法。

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

package cn.edu.heima;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class PropertiesFile {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  Properties settings = new Properties();
  try {
   settings.load(new FileInputStream("count.txt"));
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   settings.setProperty("count", String.valueOf(0));
  } catch (IOException e) {
   // TODO Auto-generated catch block
   settings.setProperty("count", String.valueOf(0));
  }
  int c = Integer.parseInt(settings.getProperty("count")) + 1;
  System.out.println("这是第"+ c + "运行");
  
  settings.setProperty("count", new Integer(c).toString());
  try {
   settings.store(new FileOutputStream("count.txt"), "Program is used:");
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

System与Runtime类

long startTime = System.currentTimeMillis();
long endTime = System.currentTimeMillis();
System.out.print(endTime - startTime);

getProperties和setProperties方法可获取和设置Java虚拟机的属性

package cn.edu.heima;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class TestProperties {

 /**
  * @param args
  * @throws IOException
  * @throws InterruptedException
  */
 public static void main(String[] args) throws IOException, InterruptedException {
  // 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));
   
  }
  Process p = null;
  try{
  p = Runtime.getRuntime().exec("notepad.exe API.java");
  Thread.sleep(50000);
  p.destroy();
  }
  catch(Exception q){}
 }

}


与日期有关得几个类
Calendar类
 add();
 get();
 set();
 getInstance()静态方法
 GregorianCalendar子类

编程实例:
 计算距离当前日期31天后的日期时间,用"xxxx年xx月xx日xx小时:xx分xx秒"格式输出。

package cn.edu.heima;

import java.util.Calendar;

public class TestCalendar {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  //Calendar c1 = Calendar.getInstance();
  Calendar c1 = Calendar.getInstance();
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
  
  c1.add(c1.DAY_OF_YEAR, 315);
  
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
 }

}

Date类
java.text.DateFormat与java.text.SimpleDateFormat子类
利用子类中的模式字符串。

编程实例:
 将“2002-03-15”格式转换为2002年03月15日的格式。
package cn.edu.heima;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TestCalendar {

 /**
  * @param args
  * @throws ParseException
  */
 public static void main(String[] args) throws ParseException {
  // TODO Auto-generated method stub
  //Calendar c1 = Calendar.getInstance();
  Calendar c1 = Calendar.getInstance();
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
  
  c1.add(c1.DAY_OF_YEAR, 315);
  
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
  SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd");
  SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年mm月dd日");
  Date d = sdf1.parse("2003-03-15");
  System.out.println(sdf2.format(d));
 }

}

Timer与TimerTask类
schedule方法几种重载形式。指定过多久启动一个线程。
schedule(TimerTask task,long delay)指定隔多长时间执行TimerTask任务代码

schedule(TimerTask task,Date time)指定在什么时间执行

schedule(TimerTask task,long delay,long period)隔多长时间定期执行TimerTask任务代码,period指定定期执行时间间隔。

schedule(TimerTask task,Date firstTime,long period)从什么时间开定期执行。

TimerTask类实现了Runnable接口,执行任务由内部实现的run方法完成。

编程实例:
程序启动运行30秒启动Windows自带的计算机程序。

package cn.edu.heima;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class TestCalendar {

 /**
  * @param args
  * @throws ParseException
  */
 public static void main(String[] args) throws ParseException {
  // TODO Auto-generated method stub
  //Calendar c1 = Calendar.getInstance();
  Calendar c1 = Calendar.getInstance();
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
  
  c1.add(c1.DAY_OF_YEAR, 315);
  
  System.out.println(c1.get(Calendar.YEAR) + "年"
    +c1.get(Calendar.MONTH) + "月"
    + c1.get(Calendar.DAY_OF_MONTH) + "日" 
    + c1.get(Calendar.HOUR_OF_DAY) + "时:"
    + c1.get(Calendar.MINUTE) + "分"
    +c1.get(Calendar.SECOND) + "秒");
  SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-mm-dd");
  SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年mm月dd日");
  Date d = sdf1.parse("2003-03-15");
  System.out.println(sdf2.format(d));
  
  new Timer().schedule(new TimerTask() {
   
   @Override
   public void run() {
    // TODO Auto-generated method stub
    try {
     Runtime.getRuntime().exec("calc.exe");
    } catch (Exception e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    //'结束线程的方法
    //TimerTask.cancel();
    this.cancel();
   }
  }, 3000);
 }

}
---------------------- <a href="http://edu.csdn.net/heima" target="blank">android培训</a>、<a href="http://edu.csdn.net/heima" target="blank">java培训</a>、期待与您交流! ----------------------

详细请查看:<a href="http://edu.csdn.net/heima" target="blank">http://edu.csdn.net/heima</a>


 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值