java API学习记录

 

API(Application Programming Interface)

JAVA   API就是JDK中提供的各种类

1. StringStringBuffer类位于java.lang

toString方法可以把StringBuffer转换为String

String x = "a"+4+"c";

String x = new StringBuffer().append("a").append(4).append("c").toString();

字符串常量实际上就是一种特殊的匿名String对象

Equals可以用来比较是否是同一个对象,==如果两个字符串一样的话就相等了

System.in.read();可以从键盘读取一个字节,需要捕捉IOException异常

参考类:

public class ReadLine {

public static void main(String[] args) {

byte [] buf = new byte[1024];

String strInfo = null;

int pos = 0;

int ch = 0;

while(true){

try {

ch = System.in.read();

} catch (IOException e) {

e.printStackTrace();

}

switch(ch){

case '/r':

break;

case '/n':

strInfo = new String(buf,0,pos);

if(strInfo.equals("bye")){

return;

}

else{

System.out.println(strInfo);

pos = 0;

break;

}

default:

buf[pos++] = (byte)ch;

break;

}

}

}

}

String

构造方法:String(byte[]bytes,int offset,int length)

equlaslgnoreCase方法:可以忽略大小写

indexOf(int ch)方法:用于返回字符在字符串首次出现的位置,没有返回-1

substring(int beginIndex)方法:字符开始位置,返回字符

Substring(int beginIndex,int endIndex):返回其间的字符

StringBuffer

toString():返回一个String类型对象

Append():把一个字符串连接到StringBuffer

2.基本数据类型的对象包装类

boolean-->Boolean,char-->Character,int-->Integer...

许多方法中都使用了Object对象,如果需要使用这样的方法就必须使用包装类

把一个字符串转换成int类型可以有三种方法: intValue(),Integer.parseInt(),valueOf()

第三种方法与前两种不同的是第三种方法转换之后是一个Integer类型

3.集合类

    集合类用于存储一组对象,其中每个对象称之为元素,经常会用到的       Vector,Enumeration,ArrayList,Collection,lterator,Set,List

 (1).Vector类与Enumeration接口

  如果不能预先确定预先要保存的对象的数目,或者需要方便获得某个对象的存放   位置时,可以选择Vector

public class TestVector {

@SuppressWarnings("unchecked")

public static void main(String args[]){

Vector v = new Vector();

int b = 0;

System.out.println("please enter number:");

while(true){

try {

b = System.in.read();

} catch (IOException e) {

e.printStackTrace();

}

if(b == '/r'|| b=='/n'){

break;

}

else{

int num = b - '0';

v.addElement(new Integer(num));

//向Vector对象中加入这个整数对象

}

}

int sum = 0;

Enumeration e = v.elements();

//v.elements()返回一个Enumeration接口对象

while(e.hasMoreElements()){//如果还有元素,指示器将返回true

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

//nextElement()返回的是一个对象

//返回指示器正在指向的那个对象,并将指示器指向下一个对象

sum +=intObj.intValue();

//intValue可以把Integer对象转换为int类型

}

System.out.println(sum);

}

}

(2).Collection接口与Iterator接口

 ArrayList类实现了Collection接口

import java.io.IOException;

import java.util.ArrayList;

import java.util.Iterator;

 

public class TestCollection {

@SuppressWarnings("unchecked")

public static void main(String args[]){

ArrayList v = new ArrayList();

int b = 0;

System.out.println("please enter number:");

while(true){

try {

b = System.in.read();

} catch (IOException e) {

e.printStackTrace();

}

if(b == '/r'|| b=='/n'){

break;

}

else{

int num = b - '0';

v.add(new Integer(num));

//向ArrayList对象中加入这个整数对象

}

}

int sum = 0;

Iterator e = v.iterator();

//v.iterator()返回一个Enumeration接口对象

while(e.hasNext()){//如果还有元素,指示器将返回true

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

//next()返回的是一个对象

//返回指示器正在指向的那个对象,并将指示器指向下一个对象

sum +=intObj.intValue();

//intValue可以把Integer对象转换为int类型

}

System.out.println(sum);

}

}

ArrayList类中所有方法都是非同步的,在没有线程安全时候ArrayList效率较高

以下是JDK文档中的提示:

注意,此实现不是同步的。如果多个线程同时访问一个 ArrayList 实例,而其中至少一个线程从结构上修改了列表,那么它必须 保持外部同步。(结构上的修改是指任何添加或删除一个或多个元素的操作,或者显式调整底层数组的大小;仅仅设置元素的值不是结构上的修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用 Collections.synchronizedList 方法将该列表包装起来。这最好在创建时完成,以防止意外对列表进行不同步的访问

(3).Collection,Set,List区别:

  Set,ListCollection的子类

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

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

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

import java.util.ArrayList;

import java.util.Collections;

public class TestSort {

@SuppressWarnings("unchecked")

public static void 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());

}

}

(4).Hashtable

此类实现一个哈希表,该哈希表将键映射到相应的值。任何非 null 对象都可以用作键或值。为了成功地在哈希表中存储和获取对象,用作键的对象必须实现 hashCode 方法和 equals 方法。

 代码如下:

import java.util.Enumeration;

import java.util.Hashtable;

 

public class HashtableTest {

@SuppressWarnings("unchecked")

public static void main(String[] args) {

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",20), new Integer(3));

Enumeration e = numbers.keys();

//取出所有关键字的集合(Integer)

while(e.hasMoreElements()){

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

System.out.print(key.toString()+"=");

//key隐式的调用toString方法,可以直接写成key...

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

//这里的key是直接从hastable里面取出来的,不用再比较了

//key是hastable的一部分,这样检索比较方便

}

System.out.println(numbers.get(new  MyKey("zhangsan",18))); }

}

public class MyKey {

private String name = null;

private int age = 0;

public MyKey(String string, int i) {

this.name = string;

this.age = i;

}

public String toString(){

return name+","+age;

}

//equals方法,hashCode方法并不是被程序调用的,而是被get方法调用

//numbers.get(key)

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 int hashCode(){

return name.hashCode()+age;

}

}

  (5.Properties类是Hashtable的子类

   Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加 载。属性列表中每个键及其对应值都是一个字符串。

示例代码:

新建一个count.txt文件内容为:

#Program is used:

#Thu Apr 14 15:03:46 CST 2011

count=0

import java.util.Properties;

import java.io.*;

 

public class PropertiesFile {

public static void main(String args[]){

Properties settings = new Properties();

try {

settings.load(new FileInputStream("C://Users//姜康 //Desktop//java//count.txt"));

} catch (IOException e) {

e.printStackTrace();

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

System.out.println("!!");

}

//settings.get("count");需要转换成字符串

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

//getProperty直接得到一个字符串

System.out.println("这个第"+c+"次运行");

//settings.put("count", new Integer(c).toString());

//Integer(c).toString()把整数类型转换为string类型

//put方法可以接收非字符串对象做参数,setProperty只能是字符串

settings.setProperty("count", new Integer(c).toString());

try {

settings.store(new FileOutputStream("C://Users//姜康 //Desktop//java//count.txt"), "Program is used:");

} catch (IOException e) {

System.out.println(e.getMessage());

}

//把properties属性列表加入到输出流中,第二个参数是设置标题

}

}

(6).SystemRuntime

Exit方法,currentTimeMillis方法

JVM的系统属性

getPropertiessetProperties方法可以设置JVM的系统属性

Runtime

它封装了java命令的运行进程,不能直接创建Runtime实例,可以通过静态方法 Runtime.getRuntime获得正在运行的Runtime对象的引用。

不能通过new来创建Runtime

设置JVM属性:java -DAAA=aaa TestProperties

实例程序:

import java.util.*;

public class TestProperties {

@SuppressWarnings("unchecked")

public static void main(String []args){

Properties sp= System.getProperties();

Enumeration e = sp.propertyNames();

while(e.hasMoreElements()){

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

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

}

}

}

下面一个例子是打开一个文件,然后几秒钟后关闭

package api.test;

import java.io.IOException;

import java.util.*;

 

public class TestProperties {

@SuppressWarnings("unchecked")

public static void main(String []args){

//Process为一个类,代表JVM启动的一个子线程

Process p = null;

try {

p = Runtime.getRuntime().exec("notepad.exe C://Users// 姜康//Desktop//java//Test.java");

} catch (IOException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

try {

Thread.sleep(5000);

} catch (InterruptedException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

}

p.destroy();

}

}

  (7). 与日期和时间有关的类

DateDateFormatCalendar

Calendar类:add()方法

get()方法获得年月日,小时分秒

Set()方法修改年月日...

getInstance静态方法

GregorianCalendar子类

   import java.util.Calendar;

 

public class TestCalendar {

@SuppressWarnings("static-access")

public static void main(String[] args) {

Calendar c1 = Calendar.getInstance();

//得到Calendar类的实例对象,也可以用new来产生

System.out.print(c1.get(c1.YEAR)+"年"+c1.get(c1.MONTH)+"月"+c1.get(Calendar.DAY_OF_MONTH)+"日");

System.out.println(c1.get(c1.HOUR)+":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND));

c1.add(c1.DAY_OF_YEAR, 315);

System.out.print(c1.get(c1.YEAR)+"年"+c1.get(c1.MONTH)+"月"+c1.get(Calendar.DAY_OF_MONTH)+"日");

System.out.println(c1.get(c1.HOUR)+":"+c1.get(c1.MINUTE)+":"+c1.get(c1.SECOND));

}

}

java.text.DateFormatjava.text.Simple.DateFormat子类

 

import java.util.Date;

import java.text.ParseException;

import java.text.SimpleDateFormat;

public class TestCalendar {

public static void main(String[] args) {

SimpleDateFormat sdf1 = new     

SimpleDateFormat("yyyy-mm-dd");

SimpleDateFormat sdf2 = new

SimpleDateFormat("yyyy年mm月dd");

Date d = null;

try {

d = sdf1.parse("2003-03-15");

} catch (ParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println(sdf2.format(d));

//用于把指定对象的值输出

    }

   }

(8).Timer/TimerTask

Timer一种线程设施,用于安排以后在后台线程中执行的任务。可安排任务执行一次,或者定期重复执行。

与每个 Timer 对象相对应的是单个后台线程,用于顺序地执行所有计时器任务。计时器任务应该迅速完成。如果完成某个计时器任务的时间太长,那么它会独占计时器的任务执行线程。因此,这就可能延迟后续任务的执行,而这些任务就可能堆在一起,并且在上述令人讨厌的任务最终完成时才能够被快速连续地执行。

TimerTask由 Timer 安排为一次执行或重复执行的任务。

Schedule(TimerTask task,long delay)

Schedule(TimerTask task,Date time)

TimerTask实现Runable接口,要执行的任务由它里面实现的run方法完成

import java.util.Timer;

import java.util.TimerTask;

public class TestTimer {

public static void main(String args[]){

//使用匿名对象来完成,无法访问到Timer对象

/*new Timer().schedule({

//需要覆盖子类的run方法

public void run(){

try{

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

}catch(Exception e){

e.printStackTrace();

}

}

},1000);*/

//结束任务线程的代码

Timer tm = new Timer();

tm.schedule(new MyTimerTask(tm), 3000);

}

}

class MyTimerTask extends TimerTask{

@SuppressWarnings("unused")

private Timer tm = null;

//传递过来的是tm对象

public MyTimerTask(Timer tm){

this.tm = tm;

}

public void run(){

try{

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

}catch(Exception e){

e.printStackTrace();

}

tm.cancel();

//可以结束线程

}

}

(9) .MathRandom

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

Random类是一个伪随机数产生器

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值