|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
Java的B/s开发是通常是javaweb开发,又叫J2EE开发,J2SE是手机开发。C#的C/s和B/s开发是说.net和Asp开发。。u在这里说明一点;资深一点的Java和C#程序员都明白一点1泛型(Generic)
1.1申明
加强了java的范例平安,能够在编译时代对容器内的对象举行范例反省,在运转期不用举行范例的转换。而在j2se5之前必需在运转期静态举行容器内对象的反省及转换
削减含混的容器,能够界说甚么范例的数据放进容器
ArrayList<Integer>listOfIntegers;//<TYPE_NAME>isnewtothesyntax
IntegerintegerObject;
listOfIntegers=newArrayList<Integer>();//<TYPE_NAME>isnewtothesyntax
listOfIntegers.add(newInteger(10));//只能是Integer范例
integerObject=listOfIntegers.get(0);//掏出对象不必要转换
1.2用法
声明及实例化泛型类:
HashMap<String,Float>hm=newHashMap<String,Float>();
file://不克不及利用原始范例
GenList<int>nList=newGenList<int>();file://编译毛病
J2SE5.0今朝不撑持原始范例作为范例参数(typeparameter)
界说泛型接口:
publicinterfaceGenInterface<T>{
voidfunc(Tt);
}
界说泛型类:
publicclassArrayList<ItemType>{...}
publicclassGenMap<T,V>{...}
例1:
publicclassMyList<Element>extendsLinkedList<Element>
{
publicvoidswap(inti,intj)
{
Elementtemp=this.get(i);
this.set(i,this.get(j));
this.set(j,temp);
}
publicstaticvoidmain(String[]args)
{
MyList<String>list=newMyList<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:
publicclassGenList<T>{
privateT[]elements;
privateintsize=0;
privateintlength=0;
publicGenList(intsize){
elements=(T[])newObject[size];
this.size=size;
}
publicTget(inti){
if(i<length){
returnelements;
}
returnnull;
}
publicvoidadd(Te){
if(length<size-1)
elements[length++]=e;
}
}
泛型办法:
publicclassTestGenerics{
public<T>StringgetString(Tobj){file://完成了一个泛型办法
returnobj.toString();
}
publicstaticvoidmain(String[]args){
TestGenericst=newTestGenerics();
Strings="Hello";
Integeri=100;
System.out.println(t.getString(s));
System.out.println(t.getString(i));
}
}
1.3受限泛型
受限泛型是指范例参数的取值局限是遭到限定的.extends关头字不单单能够用来声明类的承继干系,也能够用来声明范例参数(typeparameter)的受限干系.比方,我们只必要一个寄存数字的列表,包含整数(Long,Integer,Short),实数(Double,Float),不克不及用来寄存其他范例,比方字符串(String),也就是说,要把范例参数T的取值泛型限定在Number极为子类中.在这类情形下,我们就能够利用extends关头字把范例参数(typeparameter)限定为数字
示例
publicclassLimited<TextendsNumber>{
publicstaticvoidmain(String[]args){
Limited<Integer>number;file://准确
Limited<String>str;file://编译毛病
}
}
1.4泛型与非常
范例参数在catch块中不同意呈现,可是能用在办法的throws以后。例:
importjava.io.*;
interfaceExecutor<EextendsException>{
voidexecute()throwsE;
}
publicclassGenericExceptionTest{
publicstaticvoidmain(Stringargs[]){
try{
Executor<IOException>e=newExecutor<IOException>(){
publicvoidexecute()throwsIOException{
//codeherethatmaythrowan
//IOExceptionorasubtypeof
//IOException
}
};
e.execute();
}catch(IOExceptionioe){
System.out.println("IOException:"+ioe);
ioe.printStackTrace();
}
}
}
1.5泛型的通配符"?"
"?"能够用来取代任何范例,比方利用通配符来完成print办法。
publicstaticvoidprint(GenList<?>list){})
1.6泛型的一些范围型
不克不及实例化泛型
Tt=newT();file://error
不克不及实例化泛型范例的数组
T[]ts=newT[10];file://编译毛病
不克不及实例化泛型参数数
Pair<String>[]table=newPair<String>(10);//ERROR
类的静态变量不克不及声明为范例参数范例
publicclassGenClass<T>{
privatestaticTt;file://编译毛病
}
泛型类不克不及承继自Throwable和其子类
publicGenExpection<T>extendsException{}file://编译毛病
不克不及用于基本范例int等
Pair<double>file://error
Pair<Double>file://right
2加强轮回(EnhancedforLoop)
旧的轮回
LinkedListlist=newLinkedList();
list.add("Hi");
list.add("everyone!");
list.add("Was");
list.add("the");
list.add("pizza");
list.add("good?");
for(inti=0;i<list.size();i++)
System.out.println((String)list.get(i));
file://大概用以下轮回
file://for(Iteratoriter=list.iterator();iter.hasNext();){
file://IntegerstringObject=(String)iter.next();
//...morestatementstousestringObject...
file://}
新的轮回
LinkedList<String>list=newLinkedList<String>();
list.add("Hi");
list.add("everyone!");
list.add("Was");
list.add("the");
list.add("pizza");
list.add("good?");
for(Strings:list)
System.out.println(s);
很明晰、便利,一看便知其用法
3可变参数(VariableArguments)
完成了更天真的办法参数传进体例,System.out.printf是个很好的例子
用法:voidtest(Object…args)
一个很简单了解的例子
publicstaticintadd(int...args){
inttotal=0;
for(inti=0;i<args.length;i++)
total+=args;
returntotal;
}
publicstaticvoidmain(String[]args){
inta;
a=Varargs.add(1,2,3,4,5,6,7,8,9,10);
System.out.println(a);
}
4主动完成装箱息争箱操纵(Boxing/UnboxingConversions)
申明:完成了基础范例与外覆类之间的隐式转换。基础范例至外覆类的转换称为装箱,外覆类至基础范例的转换为解箱。这些类包含
PrimitiveTypeReferenceType
booleanBoolean
byteByte
charCharacter
shortShort
intInteger
longLong
floatFloat
doubleDouble
比方,旧的完成体例
IntegerintObject;
intintPrimitive;
ArrayListarrayList=newArrayList();
intPrimitive=11;
intObject=newInteger(intPrimitive);
arrayList.put(intObject);//不克不及放进int范例,只能使Integer
新的完成体例
intintPrimitive;
ArrayListarrayList=newArrayList();
intPrimitive=11;
file://在这里intPrimitive被主动的转换为Integer范例
arrayList.put(intPrimitive);
5静态导进(StaticImports)
很复杂的工具,看一个例子:
没有静态导进
Math.sqrt(Math.pow(x,2)+Math.pow(y,2));
有了静态导进
importstaticjava.lang.Math.*;
sqrt(pow(x,2)+pow(y,2));
个中importstaticjava.lang.Math.*;就是静态导进的语法,它的意义是导进Math类中的一切static办法和属性。如许我们在利用这些办法和属性时就不用写类名。
必要注重的是默许包没法用静态导进,别的假如导进的类中有反复的办法和属性则必要写出类名,不然编译时没法经由过程。
6列举类(EnumerationClasses)
用法:publicenumName{types,….}
复杂的例子:
publicenumColors{Red,Yellow,Blue,Orange,Green,Purple,Brown,Black}
publicstaticvoidmain(String[]args){
ColorsmyColor=Colors.Red;
System.out.println(myColor);
}
又一个复杂例子:
importjava.util.*;
enumOperatingSystems{windows,unix,linux,macintosh}
publicclassEnumExample1{
publicstaticvoidmain(Stringargs[]){
OperatingSystemsos;
os=OperatingSystems.windows;
switch(os){
casewindows:
System.out.println(“YouchoseWindows!”);
break;
caseunix:
System.out.println(“YouchoseUnix!”);
break;
caselinux:
System.out.println(“YouchoseLinux!”);
break;
casemacintosh:
System.out.println(“YouchoseMacintosh!”);
break;
default:
System.out.println(“Idon’tknowyourOS.”);
break;
}
}
}
应运enum简写的例子:
importjava.util.*;
publicclassEnumTest
{
publicstaticvoidmain(String[]args)
{
Scannerin=newScanner(System.in);
System.out.print("Enterasize:(SMALL,MEDIUM,LARGE,EXTRA_LARGE)");
Stringinput=in.next().toUpperCase();
Sizesize=Enum.valueOf(Size.class,input);
System.out.println("size="+size);
System.out.println("abbreviation="+size.getAbbreviation());
if(size==Size.EXTRA_LARGE)
System.out.println("Goodjob--youpaidattentiontothe_.");
}
}
enumSize
{
SMALL("S"),MEDIUM("M"),LARGE("L"),EXTRA_LARGE("XL");
privateSize(Stringabbreviation){this.abbreviation=abbreviation;}
publicStringgetAbbreviation(){returnabbreviation;}
privateStringabbreviation;
}
enum类中具有办法的一个例子:
enumProgramFlags{
showErrors(0x01),
includeFileOutput(0x02),
useAlternateProcessor(0x04);
privateintbit;
ProgramFlags(intbitNumber){
bit=bitNumber;
}
publicintgetBitNumber(){
return(bit);
}
}
publicclassEnumBitmapExample{
publicstaticvoidmain(Stringargs[]){
ProgramFlagsflag=ProgramFlags.showErrors;
System.out.println(“Flagselectedis:“+
flag.ordinal()+
“whichis“+
flag.name());
}
}
7元数据(Metadata)
请参考
http://www-900.ibm.com/developerWorks/cn/java/j-annotate1/
http://www-900.ibm.com/developerworks/cn/java/j-annotate2.shtml
8BuildingStrings(StringBuilder类)
在JDK5.0中引进了StringBuilder类,该类的办法不是同步(synchronized)的,这使得它比StringBuffer加倍轻量级和无效。
9把持台输出(ConsoleInput)
在JDK5.0之前我们只能经由过程JOptionPane.showInputDialog举行输出,但在5.0中我们能够经由过程类Scanner在把持台举行输出操纵
比方在1.4中的输出
Stringinput=JOptionPane.showInputDialog(prompt);
intn=Integer.parseInt(input);
doublex=Double.parseDouble(input);
s=input;
在5.0中我们能够
Scannerin=newScanner(System.in);
System.out.print(prompt);
intn=in.nextInt();
doublex=in.nextDouble();
Strings=in.nextLine();
10CovariantReturnTypes(不知道怎样翻译,也许是改动前往范例)
JDK5之前我们掩盖一个办法时我们没法改动被办法的前往范例,但在JDK5中我们能够改动它
比方1.4中我们只能
publicObjectclone(){...}
...
Employeecloned=(Employee)e.clone();
可是在5.0中我们能够改动前往范例为Employee
publicEmployeeclone(){...}
...
Employeecloned=e.clone();
11格局化I/O(FormattedI/O)
增添了相似C的格局化输出输入,复杂的例子:
publicclassTestFormat{
publicstaticvoidmain(String[]args){
inta=150000,b=10;
floatc=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);
}
}
输入了局为:
15000010
249f0a
5.013.1
5.010e+003.140e+02
上面是一些格局化参数申明(摘自CoreJava2VolumeI-Fundamentals,SeventhEdition)
Table3-5.Conversionsforprintf
ConversionCharacter
Type
Example
d
Decimalinteger
159
x
Hexadecimalinteger
9f
o
Octalinteger
237
f
Fixed-pointfloating-point
15.9
e
Exponentialfloating-point
1.59E+01
g
Generalfloating-point(theshorterofeandf)
a
Hexadecimalfloatingpoint
0x1.fccdp3
s
String
Hello
c
Character
H
b
Boolean
TRUE
h
Hashcode
42628b2
tx
Dateandtime
SeeTable3-7
%
Thepercentsymbol
%
n
Theplatform-dependentlineseparator
Table3-7.DateandTimeConversionCharacters
ConversionCharacter
Type
Example
C
Completedateandtime
MonFeb0918:05:19PST2004
F
ISO8601date
2004-02-09
D
U.S.formatteddate(month/day/year)
02/09/2004
T
24-hourtime
18:05:19
r
12-hourtime
06:05:19pm
R
24-hourtime,noseconds
18:05
Y
Four-digityear(withleadingzeroes)
2004
y
Lasttwodigitsoftheyear(withleadingzeroes)
04
C
Firsttwodigitsoftheyear(withleadingzeroes)
20
B
Fullmonthname
February
borh
Abbreviatedmonthname
Feb
m
Two-digitmonth(withleadingzeroes)
02
d
Two-digitday(withleadingzeroes)
09
e
Two-digitday(withoutleadingzeroes)
9
A
Fullweekdayname
Monday
a
Abbreviatedweekdayname
Mon
j
Three-digitdayofyear(withleadingzeroes),between001and366
069
H
Two-digithour(withleadingzeroes),between00and23
18
k
Two-digithour(withoutleadingzeroes),between0and23
18
I
Two-digithour(withleadingzeroes),between01and12
06
l
Two-digithour(withoutleadingzeroes),between1and12
6
M
Two-digitminutes(withleadingzeroes)
05
S
Two-digitseconds(withleadingzeroes)
19
L
Three-digitmilliseconds(withleadingzeroes)
047
N
Nine-digitnanoseconds(withleadingzeroes)
047000000
P
Uppercasemorningorafternoonmarker
PM
p
Lowercasemorningorafternoonmarker
pm
z
RFC822numericoffsetfromGMT
-0800
Z
Timezone
PST
s
Secondssince1970-01-0100:00:00GMT
1078884319
E
Millisecondssince1970-01-0100:00:00GMT
1078884319047
Table3-6.Flagsforprintf
Flag
Purpose
Example
+
Printssignforpositiveandnegativenumbers
+3333.33
space
Addsaspacebeforepositivenumbers
|3333.33|
0
Addsleadingzeroes
003333.33
-
Left-justifiesfield
|3333.33|
(
Enclosesnegativenumberinparentheses
(3333.33)
,
Addsgroupseparators
3,333.33
#(forfformat)
Alwaysincludesadecimalpoint
3,333.
#(forxoroformat)
Adds0xor0prefix
0xcafe
^
Convertstouppercase
0XCAFE
$
Specifiestheindexoftheargumenttobeformatted;forexample,%1$d%1$xprintsthefirstargumentindecimalandhexadecimal
1599F
<
Formatsthesamevalueasthepreviousspecification;forexample,%d%<xprintsthesamenumberindecimalandhexadecimal
这里是一些复杂的先容,更具体的申明请参考:
CoreJava2VolumeI-Fundamentals,SeventhEdition
CoreJava2VolumeII-AdvancedFeatures,SeventhEdition
内里都有一些很出色的形貌,中文称号就是《Java中心手艺》。只要第七版才有J2SE5.0的先容,可是第七版仿佛还没有中文版。本文还参考了ProfessionalJavaJDK-5thEdition.
其实产生见解的过程就是训练自己发现问题,分析问题的能力。根据以上的认识我想谈下传统的学习与通过视频独立学习的优缺点: |
|