本週主題:Java中自帶的常用接口和類的使用
一、Java Number & Math 類
一般地,當我們需要使用數字的時候,我們通常使用Java內置的基本數據類型,如:byte、int、long、double 等。如:
int x = 100;
float f = 123.56f;
double d = 3.14;
byte b = 0x32;
然而,在實際開發過程中,我們經常會遇到需要使用對象,而不是內置數據類型的情形。爲了解決這個問題,Java 語言爲每一個內置數據類型提供了對應的包裝類。
所有的包裝類(Integer、Long、Byte、Double、Float、Short)都是抽象類 Number 的子類。
1、Number & Math 類常用方法
2、Math 的 floor,round 和 ceil 方法實例比較:
3、舉個Numbers和Math用法的例子:
/**
* 文件名:NumbersDemo.java
* 功能描述:Numbers和Math類操作Demo
*/
public class NumbersDemo {
public static void main(String[] args) {
double dVer = 11.5;
float fVer = -11.5f;
System.out.printf("dVer=%.2f,fVer=%.2f\n",dVer,fVer);
//ceil()返回>=給定參數的最小整數,返回類型爲雙精度浮點型
System.out.printf("Math.ceil(%.2f)=%.2f,",dVer,Math.ceil(dVer));
System.out.printf("Math.ceil(%.2f)=%.2f\n",fVer,Math.ceil(fVer));
//floor()返回<=給定參數的最大整數,返回類型爲雙精度浮點型
System.out.printf("Math.floor(%.2f)=%.2f,",dVer,Math.floor(dVer));
System.out.printf("Math.floor(%.2f)=%.2f\n",fVer,Math.floor(fVer));
// round() 表示"四捨五入",算法爲Math.floor(x+0.5) ,即將原來的數字加上 0.5 後再向下取整,
// 所以 Math.round(11.5) 的結果爲 12,Math.round(-11.5) 的結果爲 -11。
System.out.printf("Math.round(%.2f)=%d,",dVer,Math.round(dVer));
System.out.printf("Math.round(%.2f)=%d\n",fVer,Math.round(fVer));
//ceil()返回與參數最接近的整數,返回類型爲雙精度浮點型
System.out.printf("Math.rint(%.2f)=%.2f,",dVer,Math.rint(dVer));
System.out.printf("Math.rint(%.2f)=%.2f\n",fVer,Math.rint(fVer));
//parseXXX():將字符串解析爲XXX的基本數據類型
dVer = Double.parseDouble("11.5"); //parseDouble() 返回一個基本數據類型
Double dObj = Double.valueOf("11.5"); //valueOf() 返回一個基本數據類型的包裝類對象
System.out.println("dVer="+dVer+",dObj="+dObj.toString());
int iVer = (int)Double.parseDouble("11.5");
Integer iObj = Double.valueOf("-11.5").intValue();
System.out.println("iVer="+iVer+",iObj="+iObj.toString());
System.out.println("dObj.compareTo(dVer):"+dObj.compareTo(dVer));
System.out.println("dObj.equals(dVer):"+dObj.equals(dVer));
System.out.println("Math.pow(3,2):"+Math.pow(3,2));
System.out.println("輸出5個1~100之間的隨機數:");
for (int i = 0; i < 5; i++) {
System.out.print((Math.round(Math.random()*100))+" ");
}
}
}
運行結果:
二、Java 數據結構
Java工具包提供了強大的數據結構。在Java中的數據結構主要包括以下幾種接口和類:
-
枚舉(Enumeration)
-
位集合(BitSet)
-
向量(Vector)
-
棧(Stack)
-
字典(Dictionary)
-
哈希表(Hashtable)
-
屬性(Properties)
以上這些類是傳統遺留的,在Java2中引入了一種新的框架--集合框架(Collection),我們後面再討論。
對這些Java經常要使用的接口和類,舉幾個簡單的例子加以說明:
1、枚舉(Enumeration)和向量(Vector)操作Demo:
import java.util.Enumeration;
import java.util.Vector;
/**
* 文件名:EnumerationDemo.java
* 功能描述:枚舉接口用法Demo
*/
public class EnumerationDemo {
public static void main(String[] args) {
Enumeration<String> weekDays; //聲明一個枚舉類對象
Vector<String> weekDayNames = new Vector<String>(); //Vector:向量類,類似於一個可變數組
weekDayNames.add("星期一");
weekDayNames.add("星期二");
weekDayNames.add("星期三");
weekDayNames.add("星期四");
weekDayNames.add("星期五");
weekDayNames.add("星期六");
weekDayNames.add("星期日");
weekDays = weekDayNames.elements(); //取出向量對象中的所有元素,放置到枚舉對象中
while(weekDays.hasMoreElements()) {
System.out.println(weekDays.nextElement());
}
}
}
2、位集合(BitSet)操作Demo:
import com.sun.org.apache.xalan.internal.xsltc.dom.BitArray;
import java.util.Arrays;
import java.util.BitSet;
/**
* 文件名:BitSetDemo.java
* 功能描述:
*/
public class BitSetDemo {
public static void main(String[] args) {
BitSet bits1 = new BitSet(16);
BitSet bits2 = new BitSet(16);
for (int i = 0; i < 16; i++) {
if(i%2 == 0)
bits1.set(i);
if(i%5 == 0)
bits2.set(i);
}
System.out.printf("bits1中二進制位內容爲1的索引:%s\n",bits1.toString());
System.out.printf("bits2中二進制位內容爲1的索引:%s\n",bits2.toString());
System.out.print("bits1:");
for (int i = 0; i < 16; i++) {
if (bits1.get(i))
System.out.printf("%2d",1);
else
System.out.printf("%2d",0);
}
System.out.print("\nbits2:");
for (int i = 0; i < 16; i++) {
if (bits2.get(i))
System.out.printf("%2d",1);
else
System.out.printf("%2d",0);
}
bits1.and(bits2);
System.out.printf("\nbits1和bits2進行[與]運算後:%s\n",bits1);
System.out.print("bits1:");
for (int i = 0; i < 16; i++) {
if (bits1.get(i))
System.out.printf("%2d",1);
else
System.out.printf("%2d",0);
}
bits1.or(bits2);
System.out.printf("\nbits1和bits2進行[或]運算後:%s\n",bits1);
System.out.print("bits1:");
for (int i = 0; i < 16; i++) {
if (bits1.get(i))
System.out.printf("%2d",1);
else
System.out.printf("%2d",0);
}
bits1.xor(bits2);
System.out.printf("\nbits1和bits2進行[異或]運算後:%s\n",bits1);
System.out.print("bits1:");
for (int i = 0; i < 16; i++) {
if (bits1.get(i))
System.out.printf("%2d",1);
else
System.out.printf("%2d",0);
}
}
}
3、棧(Stack)操作Demo:
import java.util.EmptyStackException;
import java.util.Stack;
/**
* 文件名:StackDemo.java
* 功能描述:Stack類使用Demo
*/
public class StackDemo {
static void showPush(Stack<Integer> st, int v) {
st.push(new Integer(v));//壓入一個數據至棧中:入棧
System.out.print("執行:push("+v+")後,");
System.out.println("stack:"+st);
}
static void showPop(Stack<Integer> st) {
int v = (Integer) st.pop(); //從棧中取數:出棧
System.out.print("執行:pop() -> 取出 "+v+" 後,");
System.out.println("stack:"+st);
}
public static void main(String[] args) {
Stack<Integer> st = new Stack<Integer>();
System.out.println("stack:" + st);
showPush(st,10);
showPush(st,20);
showPush(st,30);
if (!st.isEmpty())
System.out.println("st.peek() -> 取出棧頂內容:"+st.peek());
int x = st.search(20);
System.out.println("st.search(20) -> 查詢20在棧中的位置爲:"+x);
showPop(st);
showPop(st);
showPop(st);
try {
showPop(st); //之前已所數據取完了,此語句會拋出一個“空棧”異常
} catch (EmptyStackException e) {
System.out.println("捕獲到一個對空棧進行訪問的異常!");
}
}
}
4、字典(Dictionary)操作Demo:
Dictionary 類是一個抽象類,用來存儲鍵/值對,作用和Map類相似。Dictionary類已經過時了。在實際開發中,你可以實現Map接口來獲取鍵/值的存儲功能。
給出鍵和值,你就可以將值存儲在Dictionary對象中。一旦該值被存儲,就可以通過它的鍵來獲取它。所以和Map一樣, Dictionary 也可以作爲一個鍵/值對列表。
Dictionary定義的抽象方法如下表所示:
5、哈希表(Hashtable)操作Demo:
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
/**
* 文件名:HashTableDemo.java
* 功能描述:哈希表測試Demo
*/
public class HashTableDemo {
public static void main(String[] args) {
Hashtable balance = new Hashtable();
balance.put("張三",new Double(100.00));
balance.put("李四",new Double(200.00));
balance.put("王五",new Double(300.00));
balance.put("錢六",new Double(400.00));
balance.put("孫七",new Double(500.00));
Enumeration names;
String str;
names = balance.keys();
while(names.hasMoreElements()) {
str = names.nextElement().toString();
System.out.println(str + " : " + balance.get(str));
}
Scanner input = new Scanner(System.in);
System.out.print("請輸入要查找的帳號:");
String key = input.nextLine();
if (balance.containsKey(key)) {
double x = (Double)balance.get(key);
System.out.println("變動之前的餘額爲:");
System.out.println(x);
balance.put(key,x+500);
System.out.println("增加500之後的餘額爲:");
System.out.println(balance.get(key));
}
else {
System.out.println("key爲:"+key+" 的帳號未找到!");
}
input.close();
}
}
6、屬性(Properties)操作Demo:
Properties 繼承於 Hashtable,Properties 類表示了一個持久的屬性集。屬性列表中每個鍵及其對應值都是一個字符串。Properties 類被許多Java類使用。例如,在獲取環境變量時它就作爲System.getProperties()方法的返回值。
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
/**
* 文件名:PropertiesDemo.java
* 功能描述:
*/
public class PropertiesDemo {
public static void main(String[] args) {
Properties dbSrvConnInfo = new Properties();
dbSrvConnInfo.put("SrvIp","172.18.4.13");
dbSrvConnInfo.put("dbType","MySQL");
dbSrvConnInfo.put("dbName","student");
dbSrvConnInfo.put("loginName","root");
dbSrvConnInfo.put("loginPwd","abc@123");
System.out.println("使用Iterator讀取信息:");
Set set = dbSrvConnInfo.keySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
String key = iterator.next().toString();
String value = dbSrvConnInfo.get(key).toString();
System.out.println(key+" : "+value);
}
System.out.println("---------------------------------------");
System.out.println("使用Enumeration讀取信息:");
Enumeration keys = dbSrvConnInfo.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement().toString();
System.out.println(key+":"+dbSrvConnInfo.get(key));
}
}
}
三、演示DEMO源代碼在github上的倉庫地址:
https://github.com/xieyunc/java_demo.git