商業(yè)源碼熱門(mén)下載www.html.org.cn
1.1 說(shuō)明
增強(qiáng)了java的類(lèi)型安全,可以在編譯期間對(duì)容器內(nèi)的對(duì)象進(jìn)行類(lèi)型檢查,在運(yùn)行期不必進(jìn)行類(lèi)型的轉(zhuǎn)換。而在j2se5之前必須在運(yùn)行期動(dòng)態(tài)進(jìn)行容器內(nèi)對(duì)象的檢查及轉(zhuǎn)換
減少含糊的容器,可以定義什么類(lèi)型的數(shù)據(jù)放入容器
arraylist<integer> listofintegers; // <type_name> is new to the syntax
integer integerobject;
listofintegers = new arraylist<integer>(); // <type_name> is new to the syntax
listofintegers.add(new integer(10)); // 只能是integer類(lèi)型
integerobject = listofintegers.get(0); // 取出對(duì)象不需要轉(zhuǎn)換
1.2 用法
聲明及實(shí)例化泛型類(lèi):
hashmap<string,float> hm = new hashmap<string,float>();
file://不能使用原始類(lèi)型
genlist<int> nlist = new genlist<int>(); file://編譯錯(cuò)誤
j2se 5.0目前不支持原始類(lèi)型作為類(lèi)型參數(shù)(type parameter)
定義泛型接口:
public interface geninterface<t> {
void func(t t);
}
定義泛型類(lèi):
public class arraylist<itemtype> { ... }
public class genmap<t, v> { ... }
例1:
public class mylist<element> extends linkedlist<element>
{
public void swap(int i, int j)
{
element temp = this.get(i);
this.set(i, this.get(j));
this.set(j, temp);
}
public static void main(string[] args)
{
mylist<string> list = new mylist<string>();
list.add("hi");
list.add("andy");
system.out.println(list.get(0) + " " + list.get(1));
list.swap(0,1);
system.out.println(list.get(0) + " " + list.get(1));
}
}
例2:
public class genlist <t>{
private t[] elements;
private int size = 0;
private int length = 0;
public genlist(int size) {
elements = (t[])new object[size];
this.size = size;
}
public t get(int i) {
if (i < length) {
return elements[i];
}
return null;
}
public void add(t e) {
if (length < size - 1)
elements[length++] = e;
}
}
泛型方法:
public class testgenerics{
public <t> string getstring(t obj) { file://實(shí)現(xiàn)了一個(gè)泛型方法
return obj.tostring();
}
public static void main(string [] args){
testgenerics t = new testgenerics();
string s = "hello";
integer i = 100;
system.out.println(t.getstring(s));
system.out.println(t.getstring(i));
}
}
1.3 受限泛型
受限泛型是指類(lèi)型參數(shù)的取值范圍是受到限制的. extends關(guān)鍵字不僅僅可以用來(lái)聲明類(lèi)的繼承關(guān)系, 也可以用來(lái)聲明類(lèi)型參數(shù)(type parameter)的受限關(guān)系.例如, 我們只需要一個(gè)存放數(shù)字的列表, 包括整數(shù)(long, integer, short), 實(shí)數(shù)(double, float), 不能用來(lái)存放其他類(lèi)型, 例如字符串(string), 也就是說(shuō), 要把類(lèi)型參數(shù)t的取值泛型限制在number極其子類(lèi)中.在這種情況下, 我們就可以使用extends關(guān)鍵字把類(lèi)型參數(shù)(type parameter)限制為數(shù)字
示例
public class limited<t extends number> {
public static void main(string[] args) {
limited<integer> number; file://正確
limited<string> str; file://編譯錯(cuò)誤
}
}
1.4 泛型與異常
類(lèi)型參數(shù)在catch塊中不允許出現(xiàn),但是能用在方法的throws之后。例:
import java.io.*;
interface executor<e extends exception> {
void execute() throws e;
}
public class genericexceptiontest {
public static void main(string args[]) {
try {
executor<ioexception> e = new executor<ioexception>() {
public void execute() throws ioexception{
// code here that may throw an
// ioexception or a subtype of
// ioexception
}
};
e.execute();
} catch(ioexception ioe) {
system.out.println("ioexception: " + ioe);
ioe.printstacktrace();
}
}
}
1.5 泛型的通配符"?"
"?"可以用來(lái)代替任何類(lèi)型, 例如使用通配符來(lái)實(shí)現(xiàn)print方法。
public static void print(genlist<?> list) {})
1.6 泛型的一些局限型
不能實(shí)例化泛型
t t = new t(); file://error
不能實(shí)例化泛型類(lèi)型的數(shù)組
t[] ts= new t[10]; file://編譯錯(cuò)誤
不能實(shí)例化泛型參數(shù)數(shù)
pair<string>[] table = new pair<string>(10); // error
類(lèi)的靜態(tài)變量不能聲明為類(lèi)型參數(shù)類(lèi)型
public class genclass<t> {
private static t t; file://編譯錯(cuò)誤
}
泛型類(lèi)不能繼承自throwable以及其子類(lèi)
public genexpection<t> extends exception{} file://編譯錯(cuò)誤
不能用于基礎(chǔ)類(lèi)型int等
pair<double> file://error
pair<double> file://right
舊的循環(huán)
linkedlist list = new linkedlist();
list.add("hi");
list.add("everyone!");
list.add("was");
list.add("the");
list.add("pizza");
list.add("good?");
for (int i = 0; i < list.size(); i++)
system.out.println((string) list.get(i));
file://或者用以下循環(huán)
file://for(iterator iter = list.iterator(); iter.hasnext(); ) {
file://integer stringobject = (string)iter.next();
// ... more statements to use stringobject...
file://}
新的循環(huán)
linkedlist<string> list = new linkedlist<string>();
list.add("hi");
list.add("everyone!");
list.add("was");
list.add("the");
list.add("pizza");
list.add("good?");
for (string s : list)
system.out.println(s);
很清晰、方便,一看便知其用法
實(shí)現(xiàn)了更靈活的方法參數(shù)傳入方式,system.out.printf是個(gè)很好的例子
用法:void test(object … args)
一個(gè)很容易理解的例子
public static int add(int ... args){
int total = 0;
for (int i = 0; i < args.length; i++)
total += args[i];
return total;
}
public static void main(string[] args){
int a;
a = varargs.add(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
system.out.println(a);
}
說(shuō)明:實(shí)現(xiàn)了基本類(lèi)型與外覆類(lèi)之間的隱式轉(zhuǎn)換?;绢?lèi)型至外覆類(lèi)的轉(zhuǎn)換稱(chēng)為裝箱,外覆類(lèi)至基本類(lèi)型的轉(zhuǎn)換為解箱。這些類(lèi)包括
primitive type reference type
boolean boolean
byte byte
char character
short short
int integer
long long
float float
double double
例如,舊的實(shí)現(xiàn)方式
integer intobject;
int intprimitive;
arraylist arraylist = new arraylist();
intprimitive = 11;
intobject = new integer(intprimitive);
arraylist.put(intobject); // 不能放入int類(lèi)型,只能使integer
新的實(shí)現(xiàn)方式
int intprimitive;
arraylist arraylist = new arraylist();
intprimitive = 11;
file://在這里intprimitive被自動(dòng)的轉(zhuǎn)換為integer類(lèi)型
arraylist.put(intprimitive);
很簡(jiǎn)單的東西,看一個(gè)例子:
沒(méi)有靜態(tài)導(dǎo)入
math.sqrt(math.pow(x, 2) + math.pow(y, 2));
有了靜態(tài)導(dǎo)入
import static java.lang.math.*;
sqrt(pow(x, 2) + pow(y, 2));
其中import static java.lang.math.*;就是靜態(tài)導(dǎo)入的語(yǔ)法,它的意思是導(dǎo)入math類(lèi)中的所有static方法和屬性。這樣我們?cè)谑褂眠@些方法和屬性時(shí)就不必寫(xiě)類(lèi)名。
需要注意的是默認(rèn)包無(wú)法用靜態(tài)導(dǎo)入,另外如果導(dǎo)入的類(lèi)中有重復(fù)的方法和屬性則需要寫(xiě)出類(lèi)名,否則編譯時(shí)無(wú)法通過(guò)。
用法:public enum name {types, ….}
簡(jiǎn)單的例子:
public enum colors {red, yellow, blue, orange, green, purple, brown, black}
public static void main(string[] args){
colors mycolor = colors.red;
system.out.println(mycolor);
}
又一個(gè)簡(jiǎn)單例子:
import java.util.*;
enum operatingsystems {windows, unix, linux, macintosh}
public class enumexample1 {
public static void main(string args[]) {
operatingsystems os;
os = operatingsystems.windows;
switch(os) {
case windows:
system.out.println(“you chose windows!”);
break;
case unix:
system.out.println(“you chose unix!”);
break;
case linux:
system.out.println(“you chose linux!”);
break;
case macintosh:
system.out.println(“you chose macintosh!”);
break;
default:
system.out.println(“i don’t know your os.”);
break;
}
}
}
應(yīng)運(yùn)enum簡(jiǎn)寫(xiě)的例子:
import java.util.*;
public class enumtest
{
public static void main(string[] args)
{
scanner in = new scanner(system.in);
system.out.print("enter a size: (small, medium, large, extra_large) ");
string input = in.next().touppercase();
size size = enum.valueof(size.class, input);
system.out.println("size=" + size);
system.out.println("abbreviation=" + size.getabbreviation());
if (size == size.extra_large)
system.out.println("good job--you paid attention to the _.");
}
}
enum size
{
small("s"), medium("m"), large("l"), extra_large("xl");
private size(string abbreviation) { this.abbreviation = abbreviation; }
public string getabbreviation() { return abbreviation; }
private string abbreviation;
}
enum類(lèi)中擁有方法的一個(gè)例子:
enum programflags {
showerrors(0x01),
includefileoutput(0x02),
usealternateprocessor(0x04);
private int bit;
programflags(int bitnumber) {
bit = bitnumber;
}
public int getbitnumber() {
return(bit);
}
}
public class enumbitmapexample {
public static void main(string args[]) {
programflags flag = programflags.showerrors;
system.out.println(“flag selected is: “ +
flag.ordinal() +
“ which is “ +
flag.name());
}
}
請(qǐng)參考
http://www-900.ibm.com/developerworks/cn/java/j-annotate1/
http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml
在jdk5.0中引入了stringbuilder類(lèi),該類(lèi)的方法不是同步(synchronized)的,這使得它比stringbuffer更加輕量級(jí)和有效。
在jdk5.0之前我們只能通過(guò)joptionpane.showinputdialog進(jìn)行輸入,但在5.0中我們可以通過(guò)類(lèi)scanner在控制臺(tái)進(jìn)行輸入操作
例如在1.4中的輸入
string input = joptionpane.showinputdialog(prompt);
int n = integer.parseint(input);
double x = double.parsedouble(input);
s = input;
在5.0中我們可以
scanner in = new scanner(system.in);
system.out.print(prompt);
int n = in.nextint();
double x = in.nextdouble();
string s = in.nextline();
jdk5之前我們覆蓋一個(gè)方法時(shí)我們無(wú)法改變被方法的返回類(lèi)型,但在jdk5中我們可以改變它
例如1.4中我們只能
public object clone() { ... }
...
employee cloned = (employee) e.clone();
但是在5.0中我們可以改變返回類(lèi)型為employee
public employee clone() { ... }
...
employee cloned = e.clone();
增加了類(lèi)似c的格式化輸入輸出,簡(jiǎn)單的例子:
public class testformat{
public static void main(string[] args){
int a = 150000, b = 10;
float c = 5.0101f, d = 3.14f;
system.out.printf("%4d %4d%n", a, b);
system.out.printf("%x %x%n", a, b);
system.out.printf("%3.2f %1.1f%n", c, d);
system.out.printf("%1.3e %1.3e%n", c, d*100);
}
}
輸出結(jié)果為:
150000 10
249f0 a
5.01 3.1
5.010e+00 3.140e+02
下面是一些格式化參數(shù)說(shuō)明(摘自core java 2 volume i - fundamentals, seventh edition)
table 3-5. conversions for printf
conversion character | type | example |
d | decimal integer | 159 |
x | hexadecimal integer | 9f |
o | octal integer | 237 |
f | fixed-point floating-point | 15.9 |
e | exponential floating-point | 1.59e+01 |
g | general floating-point (the shorter of e and f) | |
a | hexadecimal floating point | 0x1.fccdp3 |
s | string | hello |
c | character | h |
b | boolean | true |
h | hash code | 42628b2 |
tx | date and time | see table 3-7 |
% | the percent symbol | % |
n | the platform-dependent line separator |
table 3-7. date and time conversion characters
conversion character | type | example |
c | complete date and time | mon feb 09 18:05:19 pst 2004 |
f | iso 8601 date | 2004-02-09 |
d | u.s. formatted date (month/day/year) | 02/09/2004 |
t | 24-hour time | 18:05:19 |
r | 12-hour time | 06:05:19 pm |
r | 24-hour time, no seconds | 18:05 |
y | four-digit year (with leading zeroes) | 2004 |
y | last two digits of the year (with leading zeroes) | 04 |
c | first two digits of the year (with leading zeroes) | 20 |
b | full month name | february |
b or h | abbreviated month name | feb |
m | two-digit month (with leading zeroes) | 02 |
d | two-digit day (with leading zeroes) | 09 |
e | two-digit day (without leading zeroes) | 9 |
a | full weekday name | monday |
a | abbreviated weekday name | mon |
j | three-digit day of year (with leading zeroes), between 001 and 366 | 069 |
h | two-digit hour (with leading zeroes), between 00 and 23 | 18 |
k | two-digit hour (without leading zeroes), between 0 and 23 | 18 |
i | two-digit hour (with leading zeroes), between 01 and 12 | 06 |
l | two-digit hour (without leading zeroes), between 1 and 12 | 6 |
m | two-digit minutes (with leading zeroes) | 05 |
s | two-digit seconds (with leading zeroes) | 19 |
l | three-digit milliseconds (with leading zeroes) | 047 |
n | nine-digit nanoseconds (with leading zeroes) | 047000000 |
p | uppercase morning or afternoon marker | pm |
p | lowercase morning or afternoon marker | pm |
z | rfc 822 numeric offset from gmt | -0800 |
z | time zone | pst |
s | seconds since 1970-01-01 00:00:00 gmt | 1078884319 |
e | milliseconds since 1970-01-01 00:00:00 gmt | 1078884319047 |
table 3-6. flags for printf
flag | purpose | example |
+ | prints sign for positive and negative numbers | +3333.33 |
space | adds a space before positive numbers | | 3333.33| |
0 | adds leading zeroes | 003333.33 |
- | left-justifies field | |3333.33 | |
( | encloses negative number in parentheses | (3333.33) |
, | adds group separators | 3,333.33 |
# (for f format) | always includes a decimal point | 3,333. |
# (for x or o format) | adds 0x or 0 prefix | 0xcafe |
^ | converts to upper case | 0xcafe |
$ | specifies the index of the argument to be formatted; for example, %1$d %1$x prints the first argument in decimal and hexadecimal | 159 9f |
< | formats the same value as the previous specification; for example, %d %<x prints the same number in decimal and hexadecimal |
這里是一些簡(jiǎn)單的介紹,更詳細(xì)的說(shuō)明請(qǐng)參考:
core java 2 volume i - fundamentals, seventh edition
core java 2 volume ii - advanced features, seventh edition
里面都有一些很精彩的描述,中文名稱(chēng)就是《java核心技術(shù)》。只有第七版才有j2se5.0的介紹,但是第七版好像還沒(méi)有中文版。本文還參考了professional java jdk - 5th edition.
|
新聞熱點(diǎn)
疑難解答
圖片精選