一. String类和StringBuffer类
1. String类对象中的内容一旦被初始化就不能再改变
2. StringBuffer类用于封装内容可以改变的字符串
3. 字符串常量实际上是一种特殊的匿名String对象
读取字符时,用空格坐结束时,要让’\r’break,否则会将\r读入
比较两个字符串的内容是否相等用equals()方法
二. 基本数据类型包装类的作用
将字符串转换成整数的编程举例
在屏幕上打印出一个星号(*)组成的矩形,矩形的宽度和高度通过启动程序时传递给main方法的参数指定,并比较下面两段代码的运行效率
String sb = newString(); StringBuffersb = new StringBuffer();
for(int i =0;i<w;j++){ for(intj = 0;j<w;j++){
sb = sb + ‘*’; sb.append(‘*’);
} }
左:每循环一次创建一个String对象
右:在外部创建了一个StringBuffer对象,不用每次循环在创建,更具效率
三. 集合类
集合类会用于储存一组对象,其中的每个对象称之为元素,经常会用到的有Vector、Enumeration、ArrayList、Collection、lterator、Set、List、等集合类和接口。
1.Vector类与Enumeration接口
System.in.read()读入一个asc2的十进制数,
Enumeration用于读入Vector中的数据
例子:
public class TestVector {
public static void main(String[]args) {
Vectorv = newVector();
System.out.println("请输入数字:");
int b = 0;
while(true){
try {
b =System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(b =='\r' || b =='\n')
break;
else{
int num = b -'0';
v.addElement(newInteger(num));
}
}
int sum = 0;
Enumeratione = v.elements();
while(e.hasMoreElements()){
IntegerintObj = (Integer)e.nextElement();
sum +=intObj.intValue();
}
System.out.println(sum);
}
}
2.Collection接口与lterator接口
什么时候用一,什么时候用二?
当用线程时一是安全的,但是当不用线程时将占用更大的内存
当不用线程时二的效率更高,但用线程是需要自己编写安全性问题
例子:
public class TestCollection {
public static void main(String[]args) {
ArrayListv = newArrayList();
System.out.println("请输入数字:");
int b = 0;
while(true){
try {
b =System.in.read();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(b =='\r' || b =='\n')
break;
else{
int num = b -'0';
v.add(newInteger(num));
}
}
int sum = 0;
Iteratore = v.iterator();
while(e.hasNext()){
IntegerintObj = (Integer)e.next();
sum +=intObj.intValue();
}
System.out.println(sum);
}
}
3. Collection、set、list、区别
a)Collection各元素对象之间没有指定的顺序,允许有重复元素和多个null元素对象
b)Set各元素对象之间没有指定的顺序,不允许有重复元素,最多允许一个null元素对象
c)List各元素对象之间有指定顺序,允许有重复元素和多个null元素对象
Collections不是集合类对象,但是提供了操作集合类对象的方法
四Hashtable
Hashtable不仅可以像Vector一样动态存储一系列的对象,而且对存储的每一个对象(称为值)都要安排另一个对象(称为关键字)与之相关联。
Hashtablenumbers = new Hashtable(); Integern = (Integer)numbers.get(“two”);
number.put(“one”,newInteger(1)); if(n!= null){
number.put(“two”,newInteger(2)); System.out.println(“two=”+ n);
number.put(“three”,newInteger(3)); }
存储(关键字不能重复) 读取(通过关键字)
用作关键字的类必须覆盖Object.hashCode方法和Object.equals方法。
这两个方法是为java服务的,必须覆盖,
例子:
Mykey:
public class MyKey {
private Stringname =null;
private int age = 0;
public MyKey(String name,int age) {
this.name = name;
this.age = age;
}
public boolean equals(Object obj){
if(objinstanceof MyKey){
MyKey objTemp = (MyKey)obj;
if(name.equals(objTemp.name) &&age == objTemp.age){
return true;
}else{
return false;
}
}else{
return false;
}
}
public int hashCode(){
returnname.hashCode() +age;
}
@Override
public String toString() {
// TODO Auto-generatedmethod stub
returnname +"," + age;
}
}
HashTable:
public class HashtableTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generatedmethod stub
Hashtable numbers = newHashtable();
numbers.put(new MyKey("张三",18),new Integer(1));
numbers.put(new MyKey("李四",25),new Integer(2));
numbers.put(new MyKey("王五",68),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));
}
System.out.println(numbers.get(new MyKey("张三", 18)));
}
}
四. Properties类
1) Properties类是Hashtable的子类
2) 增加了将Hashtable对象中德关键字和值保存到文件和从文件中读取关键字和值保存到文件和从文件中读取关键字和值到Hashtable对象中的方法
3) 如果要用Properties.store方法存储Properties对象中的内容,每个属性的关键字和值都必须是String类型
编程举例:使用Properties把程序的启动运行次数记录在某个文件中,每次运行时打印出它的运行次数。
用于对文件的操作。
public class PropertiesFile {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generatedmethod stub
long startTime = System.currentTimeMillis();
Properties settings = new Properties();
try {
settings.load(new FileInputStream("count.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generatedcatch block
//e.printStackTrace();
settings.setProperty("count", String.valueOf(0));
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
//settings.get("count")
int c = Integer.parseInt(settings.getProperty("count")) + 1;
System.out.println("这是第" + c +"运行");
//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 (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generatedcatch block
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.print("totalrunning time :" + (endTime - startTime));
}
}
五. System与Runtime类
System类: 1.exit方法,终止内容
2.currentTimeMillis方法,算出从1970年x月x日到现在有多少毫秒
3.java虚拟机的系统属性
4.getProperties和setProperties,获取和设置jvm属性
Runtime类:1.Runtime.getRuntime静态方法
编程实例:在java程序中启动一个windows记事本程序运行实例,并在该运行实例中打开这个java程序的源文件,启动的记事本程序5秒钟后被关闭。
public class TestProperties {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generatedmethod 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.exeTestProperties.java");
Thread.sleep(3000);
p.destroy();
} catch (Exception e1) {
// TODO Auto-generatedcatch block
e1.printStackTrace();
}
}
}
六.与日期和时间有关的类
最常用的几个类:Date、DateFormat、和Calendar
Calendar类:
Calendar.add方法
Calendar.get方法
Calendar.getInstance静态方法
GregorianCalendar子类
编程事例:计算出距当前日期时间315天后的日期时间,并用
“xxxx年xx月xx日:xx小时:xx分:xx秒”的格式输出。
System.out.println(cl.get(Calendar.YEAR) +"年" + cl.get(cl.MONTH) +"月" + cl.get(cl.DAY_OF_MONTH) +"日 "
+ cl.get(cl.HOUR) +":" +cl.get(cl.MINUTE) +":" + cl.get(cl.SECOND));
cl.add(cl.DAY_OF_YEAR, 315);
System.out.println(cl.get(Calendar.YEAR) +"年" + cl.get(cl.MONTH) +"月" + cl.get(cl.DAY_OF_MONTH) +"日 "
+ cl.get(cl.HOUR) +":" + cl.get(cl.MINUTE) +":" +cl.get(cl.SECOND));
Date类:
Java.text.DateFormat与java.text.SimpleDateFormat子类
编程实例:将”2002-03-15”格式的日期字符串换成”2002年03月15日”的格式
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));
Timer与TimerTask类
1)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)
2) TimerTask类实现了Runnable接口,要执行的任务由里面的run方法来完成
编程实例:程序启动运行后30秒,启动windows自带的计算器程序
class MyTimeTask extends TimerTask{
private Timer tm;
publicMyTimeTask(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),30000);
Timer是一个子线程,不会停止,调用cancle方法以停止
六. Math类和Random类
1) Math类包含了所有用于几何和三角运算的方法
2) Random类是一个伪随机产生起
七. 学习API的方法
1. 有了某一领域的专业知识,再看一些范例程序,才能更容易掌握和理解一些新的API类
2. 不要看什么Java API大全之类的书籍
3. 结交一些程序员朋友,或上一些技术论坛