java -- API

1.String类和StringBuffer类

位于java.lang包中;

String类对象中的内容一旦被初始化就不能再改变。

StringBuffer类用于封装内容可以改变的字符串 。

用toString方法转换成String类型。

String x="a"+4+"c"; 编译时等效于

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

字符串常量(如"hello") 实际上是一种特殊的匿名String对象。 比较下面两种情况的差异:

String s1="hello";  String s2="hello";   //地址其实是相等的 。

String s1=new String("Hello");  String s2=new String("Hello");

Q: 从键盘读取字符, 遇到换行输出。字符串为"bye" 时输出结束;

public class ReadLine {
    public static void main(String[] args) {
        // TODO: Add your code here
        byte [] buf=new byte[1024];
        String strInfo=null;
        int pos=0;
        int ch=0; 
    //    System.out.print("please enter info: ".substring(13, 17));//.indexOf('r',3));
    //    String a="x"+"3"+"c"; /两条语句是等价的;/String a=new StringBuffer().append("x").append("3").append("c").toString();
    //    System.out.println(a); 
        while(true)
        {
            try{ch=System.in.read();} catch(Exception e){e.printStackTrace();}  //键盘中读取一个输入字节,返回值设置为整数;
            switch(ch)
            {
                case '
':
                    break;
                case '
':
                    strInfo=new String(buf, 0, pos);
                    //strInfo.equalsIgnoreCase();  不区分大小写比较 ;
                    if(strInfo.equals("bye"))
                    {
                        return;
                    }
                    else
                    {
                        System.out.println(strInfo);
                        pos = 0;
                        break;
                    }
                default:
                    buf[pos++] = (byte)ch;
            }    
        }
    }    
}

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

打印小矩形。

public class TestInteger {
    public static void main(String[] args) {
        // TODO: Add your code here
        int w=new Integer(args[0]).intValue();
        int h=Integer.parseInt(args[1]);
        //int h=Integer.valueOf(arge[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 和StringBuffer对象某些情况效率比较。

//以下情况StringBuffer对象较优;

String sb=new String();
for(int j= 0; j<10; j++)
{
   sb=sb+'*';
}

sb先转化成StringBuffer型, 串尾加上'*'后又利用.toString()转化成String类型, 效率低。

StringBuffer sb=new StringBuffer();
for(int i=0; i<10; i++)
{
  sb.append('*');
}

----------------

 

3.集合类

集合类用于存储一组对象, 其中的每个对象称之为元素, 经常用到的有 Vector, Enumeration, ArrayList, Collection, Iterator, Set, List等集合类和接口 .

Vector类与Enumeration接口.

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

import java.util.* ;
public class TestVector {
    public static void main(String[] args) {
        int b=0;
        Vector v=new Vector();
        System.out.println("please enter number ");
        while(true)
        {
            try{b=System.in.read();} catch(Exception e){e.printStackTrace();}
            
            if(b=='
' || b=='
')
                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接口;

编程举例: 用ArrayList和Iterator改写上面的例子程序;

import java.util.* ;
//进程独立 ; 
public class TestCollection {
    public static void main(String[] args) {
        // TODO: Add your code here
         int b=0;
        ArrayList v=new ArrayList();
        System.out.println("please enter number ");
        while(true)
        {
            try{b=System.in.read();} catch(Exception e){e.printStackTrace();}
            if(b=='
' || b=='
')
                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);
    }    
}

Collection, Set和List 的区别如下:

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

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

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

Sort排序;

import java.util.*;

public class TestSort {
    public static void main(String[] args) {
        // TODO: Add your code here
        ArrayList a1=new ArrayList();
        a1.add(new Integer(3));
        a1.add(new Integer(2));
        a1.add(new Integer(1));
        System.out.println(a1.toString());
        
        Collections.sort(a1);
        System.out.println(a1.toString());
    }    
}

 

4、Hashtable类

Hashtable不仅可以像Vector 一样动态存储一系列的对象, 而且对存储的每一个对象都要安排另一个对象与之相关联, 用作关键字的类必须覆盖Object.hashCode方法和Object.equals方法;

public class MyKey {
    private String name = null;
    private int age = 0;
    
    public MyKey(String name, int age) {
        this.name=name; this.age=age ;
    }
    //覆盖hashtable类中的equals(){} 和hashCode(){} 方法 ;
    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; 
    }
    //
    public String toString() {
        return name + "," + age;
    }

    //StringBuffer类不能被用作关键字类 ;
}
import java.util.* ;

public class HashtableTest {
    
    public static void main(String[] args) {
        
        Hashtable numbers=new Hashtable();
        numbers.put(new MyKey("zhangsan", 18),new Integer(1));
        numbers.put(new MyKey("lisi", 16),new Integer(2));
        numbers.put(new MyKey("wangwu", 10),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));
        }
        //为什么重载 equals() 和hashCode()? ->
        //numbers.put("",  );  相当于创建了一个新对象, 哈希表中存储的相当于对象中的地址, 体现了java面向对象的特性;
        //System.out.println(numbers.get(new MyKey("zhangsan", 18))) ;
    
    }    
}

 5、Properties 类

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

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

import java.util.Properties ;
import java.io.* ;

public class PropertiesFile {
    
    public static void main(String[] args) {
        long startTime=System.currentTimeMillis();
        
        //记事本记录程序运行次数 ;
        Properties settings=new Properties();
        try{settings.load(new FileInputStream("count.txt"));} 
        catch (Exception e){
            settings.setProperty("count", String.valueOf(0));
        }
        //settings.get("count") ;
        int c  =Integer.parseInt(settings.getProperty("count")) + 1;
        System.out.println("the param has ran "+ c+" times");
        // /*继承Hashtable 这个类中的方法*/ settings.put("count", new Integer(c).toString());
        settings.setProperty("count", new Integer(c).toString());
        try{settings.store(new FileOutputStream("count.txt"), "program is used: ");} catch(Exception e) {e.printStackTrace();}
        
        long endTime=System.currentTimeMillis();
        System.out.println("total running time is :"+(endTime-startTime));
        //程序运行时间 ;
    }    
}

    

System与Runtime 类 ;

System 类 ;

  --exit 方法;

  --currentTimeMillis 方法 ;

      --java 虚拟机的系统 属性;

      --getProperties 和  setProperties 方法 ;

Runtime类

       --Runtime.getRuntime 静态方法;

import java.util.* ;
public class TestProperties {
    
    public static void main(String[] args) {
        //TODO: Add your code here
        //System.setProperties();
        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 TestProperties.java"); //利用记事本启动 TestProperties.java源文件 5S; 
            //p= Runtime.getRuntime().exec("notepad exe TestProperties.java")
            Thread.sleep(5000);
            p.destroy() ;
            //关闭进程  ;
        }
        catch(Exception e1)
        {e1.printStackTrace(); }
    }    
}

 6 、与日期和时间有关的类

最常用的几个类:  Date、DateFormat 、Calendar、

Calendar类 :

      --Calendar.add方法    //计算 ;

      --Calendar.get方法    //表示-->输出 ;

      --Calendar.set方法    //修改 ; 

      --Calendar.getInstance静态方法 ;

                 --GregorianCalendar子类 ;

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

Timer与TimerTask类:

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

  schedule(TimerTask task, long  delay);

  schedule(TimerTask task, Date time);

  schedule(TimerTask task, long delay, long period);

  schedule(TimerTask task, Date firstTime, long period);

Timer Task类实现了Runnable接口, 要执行的任务由它里面实现的run方法来完成 .

编程示例:  程序启动运行后30秒运行windows下的计算机程序 ;

import java.util.* ;
import java.text.SimpleDateFormat ;
public class TestCalendar {
    
    public static void main(String[] args) {
        // TODO: Add your code here
        Calendar c=Calendar.getInstance();
        System.out.println(c.get(Calendar.YEAR)+""+c.get(Calendar.MONTH)+""+
            c.get(c.DAY_OF_MONTH)+""+c.get(c.HOUR)+":"
                +c.get(c.MINUTE)+":"+c.get(c.SECOND));
            c.add(c.DAY_OF_YEAR, 315);
        System.out.println(c.get(Calendar.YEAR)+""+c.get(Calendar.MONTH)+""+
            c.get(c.DAY_OF_MONTH)+""+c.get(c.HOUR)+":"
                +c.get(c.MINUTE)+":"+c.get(c.SECOND));
     
     SimpleDateFormat sdf1
= new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat sdf2= new SimpleDateFormat("yyyy年MM月dd日"); try { Date d= sdf1.parse("2013-03-15"); System.out.println(sdf2.format(d)) ; } catch (Exception e) { e.printStackTrace(); }

     class MyTimerTask extends TimerTask { private Timer tm=null; public MyTimerTask(Timer tm) { this.tm=tm; } public void run() { try{ Runtime.getRuntime().exec("calc.exe");} catch (Exception e) { e.printStackTrace(); } tm.cancel(); } } Timer tm= new Timer(); tm.schedule(new MyTimerTask(tm), 300); //Timer和TimerTask; /*new Timer().schedule(new TimerTask() // 匿名内置类 ; { public void run() { try{Runtime.getRuntime().exec("calc.exe");} catch (Exception e) { e.printStackTrace(); } } //public void run() {try{Runtime.getRuntime().exec("notepad.exe");} catch (Exception e){ e.printStackTrace();} } //结束任务线程的代码 ;    /**
       */
     } ,3000);
*/ } }

7、 Math和Random类 ;

Random 会产生随机数 .

原文地址:https://www.cnblogs.com/ceal/p/5317061.html