zoukankan      html  css  js  c++  java
  • 杰普Core Java课程笔记3

    ——年金波老师上课笔记

    杰普Core Java课程笔记3    1

    输入/输出(IO)    1

    IO编程步骤    1

    输入输出实例(利用PrintWriterScanner)    2

    对标准输入输出重定向:    2

    序列化    5

    两个静态方法:    7

    Java网络编程    8

    Tcp实例    8

    UDP实例    11

    简易聊天室    12

    Java 5.0新特性    16

    1.自动装箱拆箱    16

    2.增强的for循环    17

    3.System.out.printf();    18

    4.静态导入    19

    5.可变长度的参数    20

    6.泛型 Generic    20

    7.枚举     23

    8.annotation 注解    24

     

    输入/输出(IO)

    IO编程步骤

    三步骤:

    1.制定input & output

    2.input & output 进行读写

    3.回收input & output 的资源(os级别开辟的资源)

    source & idestination:文件 网络

    流:将input output进行连接

    input&output相对程序来说

    字符流:文本文件(人类可识别)(WriterReader)

    字节流:二进制文件(视频 音频 图片)(InputStreamOutputStream)

    本质上的都是二进制,java默认使用utf-8作为字符的默认编码,一个utf-8字符占用两个字节

    DateInputStream DateOnputStream :专门处理原始类型 readInt() readLong() writeInt() writeLong()

    抽象类:InputStream OutputStream

    对原始数据的读写,采用流InputStreamOutputStream,对各种基本数据类型和String类型的读写,采用流DataOutputStreamDataInputStream;对象读写采用流ObjectInputStreamObjectOutputStream

     

    序列化,将内存中的对象转换为二进制的形式进行存储(java独有) ObjectOutputStream.write

    PipedInputStream:线程间的通信

    FileInputStream ifs=new FileInputStream("E\\a.txt");

    InputStreamReader isr=new InputStreamReader(fis);

    BufferedReader br= new BufferedReader(isr);

    Scanner: 字符输入

    PrintWriter:字符输出 java.util.

    输入输出实例(利用PrintWriterScanner)

    package ch08;

    import java.io.PrintWriter;

    import java.util.Scanner;

     

    public class ScannerTest

    {

    public static void main(String []args)

    {

    Scanner scanner=new Scanner(System.in);

    PrintWriter pw=new PrintWriter(System.out);

    System.out.println("plz input something:");

    while(scanner.hasNextLine())

    {

    String input=scanner.nextLine();

    if(input.equals("exit"))

    {

    System.exit(0);

    }

    pw.println("You just input:"+input);

    pw.flush(); //刷新,对于支持缓存的流来说,要及时的进行刷新,

     

    }

    pw. close(); //关闭输出流

    scanner.close(); //关闭输入流

    }

    }

     

    对标准输入输出重定向:

    输出:默认情况是终端。

    重定向:System.setIN(InputStream in);

    System.setOut(PrintStream out);

    PrintStream ps=new PrintStream(new File("a.txt"));

    System.setOut(ps);

    System.out.println("HW");HW显示在a.txt中。不显示在终端。

    字符编码:在linux平台下。系统默认的编码是utf-8(国际编码 二个字节表示)

    win平台下,系统默认的编码是GB2312(同GBK)国标码

    iso-8859-1 latin-1 (表示西欧字符集)

    字节流

    ch11/ArrayCopyTest.java

    阀值:

    对于字节流的操作:主要通过改变缓冲区大小来提高效率

    线程通信:PipedInputStream

    PipedOutputStream

    ch11/PipedStreamTest.java

    package ch08;

    import java.io.*;

     

    public class PipedStreamTest

    {

     

    public static void main(String []args) throws Exception

    {

    PipedInputStream pis=new PipedInputStream();

    PipedOutputStream pos=new PipedOutputStream();

    pis.connect(pos);

    new Sender(pos);

    new Reciever(pis);

    }

    }

     

    class Sender implements Runnable

    {

    private PipedOutputStream pos;

    public Sender(PipedOutputStream pos)

    {

    this.pos=pos;

    new Thread(this).start();

    }

     

    public void run()

    {

    BufferedOutputStream bos=new BufferedOutputStream(pos);

    DataOutputStream dos=new DataOutputStream(bos);

    for(int i=0;i<100;i++)

    {

    try{

    dos.writeInt(i); //Reciever线程发送

    try{

    Thread.currentThread().sleep(100);

    }

    catch(InterruptedException e)

    {

    e.printStackTrace();

    }

    System.out.println("Send:" +i);

    dos.flush();

    }

    catch(IOException e){

    e.printStackTrace();

    }

    }

    try{

    dos.close();

    bos.close();

    }

    catch(Exception e){

    e.printStackTrace();

    }

    }

    }

     

    class Reciever implements Runnable

    {

    private PipedInputStream pis;

    public Reciever(PipedInputStream pis)

    {

    this.pis=pis;

    new Thread(this).start();

    }

     

    public void run()

    {

    BufferedInputStream bis=new BufferedInputStream(pis);

    DataInputStream dis=new DataInputStream(bis);

    for(int i=0;i<100;i++)

    {

    try{

    int result=dis.readInt(); //读取

    System.out.println("Recived:" +result);

    }

    catch(IOException e){

    e.printStackTrace();

    }

    }

    try{

    dis.close();

    bis.close();

    }

    catch(Exception e){

    e.printStackTrace();

    }

    }

    }

     

    序列化

    序列化:ObjectOutputStream

    反序列化:ObjectInputStream

    对于要序列话的对象必须实现java.io.Serializebale

    package ch11;

     

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.ObjectInputStream;

    import java.io.ObjectOutputStream;

     

    public class SerialTest {

    public static void main(String args[]) {

    String fileNameString = "em.ser";

    Employee emplpyee = new Employee();

    emplpyee.setAge(99);

    emplpyee.setName("john");

    emplpyee.setGender(true);

    try {

    emplpyee.save(fileNameString);

    outEm(fileNameString);

    } catch (Exception e) {

    // TODO Auto-generated catch block

    e.printStackTrace();

    }

     

    }

     

    public static void outEm(String fileName) throws Exception {

    FileInputStream fis = new FileInputStream(fileName);

    ObjectInputStream ois = new ObjectInputStream(fis);

    Object obj = ois.readObject();/* 反序列化 */

    Employee employee = (Employee) obj;

    System.out.println("From file em info:");

    System.err.println("Name:" + employee.getName());

    System.err.println("Age:" + employee.getAge());

    System.err.println("Gender:"

    + ((employee.getGender() == true) ? "Male" : "Female"));

     

    }

    }

    class Employee implements java.io.Serializable {

    private String name;

    private int age;

    private boolean gender;

     

    public Employee() {

    super();

    }

     

    public Employee(String name, int age, boolean gender) {

    super();

    this.name = name;

    this.age = age;

    this.gender = gender;

    }

     

    public String getName() {

    return name;

    }

     

    public void setName(String name) {

    this.name = name;

    }

     

    public int getAge() {

    return age;

    }

     

    public void setAge(int age) {

    this.age = age;

    }

     

    public boolean getGender() {

    return gender;

    }

     

    public void setGender(boolean gender) {

    this.gender = gender;

    }

     

    public String toString() {

    return this.getName() + this.getAge() + this.getGender();

    }

     

    public void save(String fileName) throws Exception {

    FileOutputStream fos = new FileOutputStream(fileName);

    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(this);

    oos.flush();

    oos.close();

    fos.close();

    }

    }

     

    两个静态方法:

    1.1000employee放入list中,然后序列化(List

    2。经list反序列化。然后打印出1000个。

     

    transient:对于要序列化的对象,用它修饰属性的话不会被序列化。

    RandomAccessFiles:随机访问文件 可以访问文件中的任意一个字节

    文件指针:文件指针的位置就是下一次read的开始位置。 javaio

    seek(long postition)

    0:开始位置

    end:文件的字节总数

    seek(0);read();//读第一个字节内容

     

    ch08/RandomAccessFileTest.java :byte的所有数字 -128127

    //byte的所有数字 -128 ~ 127 ,向文件中写入byte类型数据

    package ch08;

    import java.io.*;

    public class RandomAccessFileTest

    {

    public static void main(String []args) throws Exception

    {

    File file=new File("ch08/raf.db");

    RandomAccessFile raf=new RandomAccessFile(file,"rw");

    //for(int i=-128;i<128;i++)

    //for(byte i=-128;i<128;i++) //这样会死循环

    for(byte i=-128;i<127;i++)

    {

    raf.writeByte(i);

    if(i==126)

    {

    raf.writeByte(127);

    }

    System.out.println(i);

    }

    raf.seek(255);

    int result=raf.readByte();

    System.out.println(result);

    System.out.println("File-Pointer Loc:"+ raf.getFilePointer());

    raf.close();

    }

    }

     

    Java网络编程

    socket:由操作系统来分配和管理

    port:telnet 23

    oracle:1521

    port11024 系统端口

    165535 应用端口

     

    七层模型: osi

    TCP:握手, 保证通信的有效性 稳定

    UDP:不保证一定能收到消息 速度上的高效 适合做视频,实时性较高的系统 对网络要求高

     

    java

    TCPServerSocket 服务器端

    Socket 客户端

    UDPDategramSocket 用于通信

    DategramPacket 用于数据(发送和接受网络udp包)

    java.net.*

    ServerSocket ss=new ServerSocket(9999);

    Socket socket=ss.accept(); //socket 用来与连接到服务器端的客户端进行通信

    64.135.24.33

     

    客户端

    Scoket socket=new Socket(服务器的ip,服务的端口号);

    InputStream=socket.getInputStream() //获取输入流,用来读取服务器的输出

    OutputStrem=socket.getOutputStream();//获取输出流,用来想服务器发送数据

     

    Tcp实例

    Ch09\ TCPserver.java

    package ch09;

     

    import java.io.*;

    import java.net.*;

    import java.util.Scanner;

     

    public class TCPserver

    {

    public static void main(String []args)

    {

    Socket socket=null;

    ServerSocket ss=null;

    try{

    ss=new ServerSocket(9999);

    boolean flag=true;

    while(flag)

    {

    Scanner scanner=new Scanner(System.in);

    socket=ss.accept();

    InputStream in=socket.getInputStream();

    OutputStream out=socket.getOutputStream();

     

    System.out.println(socket.getInetAddress().getHostAddress()+" connected");

    PrintWriter pw=new PrintWriter(out);

    pw.println(new java.util.Date().toLocaleString());

    pw.flush();

    pw.close();

     

    if("shutdown".equals(scanner.nextLine()))

    {

    socket.close();

    ss.close();

    System.out.println("已关闭连接!");

    flag=false;

    break;

    }

    //socket.close();

    //ss.close();

    }

    //socket.close();

    //ss.close();

    }

    catch(Exception e)

    {

    e.printStackTrace();

    }

     

    }

    }

     

    //telnet 127.0.0.1 9999

     

    Ch09\ TCPclient.java

    package ch09;

    import java.io.*;

    import java.net.*;

    import java.util.Scanner;

     

    public class TCPclient

    {

    public static void main(String []args)

    {

    try{

    Socket socket=new Socket("127.0.0.1",9999);

    InputStream in= socket.getInputStream();

    OutputStream out=socket.getOutputStream();

    Scanner scanner=new Scanner(in);

    while(scanner.hasNextLine())

    {

    String message=scanner.nextLine();

    System.out.println("From Server:"+message);

    }

    in.close();

    out.close();

    socket.close();

    }

    catch(Exception e)

    {

    e.printStackTrace();

    }

    }

    }

     

    //telnet 127.0.0.1 9999

     

    DatagramPacket 封装udp

    DatagramSocket     发送和接受udp

     

    html css js div -> html5 css3 js V8

    flex:action script + mxml

    云计算:hadoop 集群

    amazon c3

    google apps

     

    UDP实例

    Ch09\ UDPserver.java

    package ch09;

     

    import java.io.*;

    import java.net.*;

    import java.util.Scanner;

     

    public class UDPServer

    {

    public static void main(String []args) throws Exception

    {

    DatagramPacket packet=null;

    DatagramSocket socket=null;

    socket=new DatagramSocket(10000); //使用10000号端口

    byte[] buffer=new byte[1024];

    packet=new DatagramPacket(buffer,buffer.length); //定义一个packet用于装将接收的数据

    int pacCount=0;

    while(true)

    {

    socket.receive(packet); //接收客户端发过来的数据包

    pacCount++;

    String string=new String(packet.getData(),0,packet.getLength());

    System.out.println("From Client:"+string+" Count:"+pacCount);

    }

    }

    }

     

    //telnet 127.0.0.1 9999

     

    Ch09\ UDPclient.java

    package ch09;

     

    import java.io.*;

    import java.net.*;

    import java.util.Scanner;

     

    public class UDPClient

    {

    public static void main(String []args) throws Exception

    {

    DatagramPacket packet=null;

    DatagramSocket socket=null;

    socket=new DatagramSocket(10002); //使用10000号端口

    SocketAddress address=new InetSocketAddress("127.0.0.1",10000); //构建要发送的包的地

    for(int i=0;i<100;i++)

    {

    String string=""+i;

    packet=new DatagramPacket(string.getBytes(),string.length(),address);

    socket.send(packet);

    System.out.println("Send:"+string+" NO."+i);

    }

    socket.close();

    }

    }

     

    //telnet 127.0.0.1 9999

     

    简易聊天室

    Ch09\ ChatServer.java

    package ch09;

     

    import java.io.*;

    import java.net.*;

    import java.util.*;

    import java.util.concurrent.ConcurrentLinkedQueue;

    import java.util.Scanner;

     

    public class ChatServer

    {

    private ServerSocket ss;

    private List list;

    //private Queue list; //解决并发安全:方法一

    private Socket socket;

    private static final int PORT=9999;

    private static final String WELCOME_MESSAGE="@Welcom to chat room !";

     

    public ChatServer()

    {

    try

    {

    list=new LinkedList();

    //list=new ConcurrentLinkedQueue(); //方法一:使用ConcurrentLinkedQueue解决并发安全

    ss=new ServerSocket(PORT);

    while(true)

    {

    socket=ss.accept();

    add(socket);

    new Handler(socket); //new一个用户连接句柄

    }

    }

    catch(Exception e)

    {

    e.printStackTrace();

    }

    }

     

    //内部类,代表着一个用户连接

    class Handler implements Runnable

    {

    private Socket socket;

    public Handler(Socket socket)

    {

    this.socket=socket;

    new Thread(this).start(); //new一个线程,并启动

    }

     

    public void run()

    {

    InputStream in=null;

    OutputStream out=null;

    try

    {

    //while(true)

    //{

    in=socket.getInputStream();

    out=socket.getOutputStream();

    Scanner scanner=new Scanner(in);

    PrintWriter pw=new PrintWriter(out); //初始化输出对象

    pw.println(WELCOME_MESSAGE); //输出欢迎信息

    pw.flush();

    while(scanner.hasNextLine()) //持续等待用户输入,获得客户的发言信息

    {

    String message=scanner.nextLine();

    broadcast(socket.getInetAddress().getHostAddress()+" says:"+message);

     

    //方法二:解决并发安全

    //broadcast_1(socket.getInetAddress().getHostAddress()+" says:"+message);

    //广播客户的发言

    }

    //pw.close();

    socket.close();

    //}

     

    //scanner.close();

    //in.close();

    //out.close();

    //socket.close();

    }

    catch(Exception e)

    {

    e.printStackTrace();

    }

    }

    }

     

    //广播客户的发言(群发)

    //解决并发安全问题,方法二

    public void broadcast_1(String message) throws Exception

    {

    int size=list.size();

    for(int i=0;i<size;i++)

    {

    Socket socket=(Socket)list.get(i);

    if(socket.isClosed()) //socket是否被关闭

    {

    System.out.println("Socket is closed,the list size is:"+list.size());

    remove(socket); //如果socket关闭了,就从list中删除

    System.out.println("after remove,the list size is:"+list.size());

    break;

    }

    else

    {

    //System.out.println("not close,list size is:"+list.size());

    OutputStream out=socket.getOutputStream();

    PrintWriter pw=new PrintWriter(out);

    pw.println(message); //把消息写到输出流

    pw.flush();

    }

    }

    }

     

     

    //广播客户的发言(群发)(使用迭代器遍历)

    public void broadcast(String message) throws Exception

    {

    Iterator it=list.iterator();

    while(it.hasNext())

    {

    Socket socket=(Socket)it.next();

    if(socket.isClosed()) //监听

    {

    System.out.println("Socket is closed,the list size is:"+list.size());

    remove(socket); //如果socket关闭了,就从list中删除

    System.out.println("after remove,the list size is:"+list.size());

    break; //解决并发安全,方法三

    }

    else

    {

    OutputStream out=socket.getOutputStream();

    PrintWriter pw=new PrintWriter(out);

    pw.println(message); //把消息写到输出流

    pw.flush();

    //pw.close();

    //out.close();

    }

    }

    }

     

    //添加用户 上线

    public void add(Object obj)

    {

    list.add(obj);

    }

     

    //删除用户 下线

    public void remove(Object obj)

    {

    list.remove(obj);

    }

     

    public static void main(String []args) throws Exception

    {

    new ChatServer();

    }

    }

    //服务端启动后,客户端只需在cmd中用telnet连接到服务端,即可发送聊天信息

    //telnet 127.0.0.1 9999

     

    Java 5.0新特性

    java版本:1.0 -> 1.4 -> 1.5 (5.0) ->7.0

     

    1.自动装箱拆箱

    boxing -> 封装(wrappper)

    封装基本类型:

    int Integer

    byte Byte

    short short

    long Long

    float Float

    double Double

    boolean Boolean

    ------------之前的做法

    char Charater (静态方法 处理字符)

    List list=new ArrayList();

    int i=0;

    Integer iInteger=new Integer(i);

    list.add(lInteger);

    ------------现在的做法

    char Charater (静态方法 处理字符)

    List list=new ArrayList();

    int i=0;

    list.add(i);

    int -> Integer 封装 装箱 boxing

    Integer -> 拆箱 unboxing

     

    java5.BoxingTest.java

    编译:

    javac -source 1.4 -d . java5\Boxing.java

     

    设置eclipse编译版本

    在项目上点右键 -> Properties -> java compiler -> compile ocmpliance level: 1.4

     

    javap -c java5.BoxingTest //查看java的汇编代码

     

    老师观点:

    不要一味的埋头干事,更重要的是要多抬头看路,快速的接受掌握新的东西。

    没人会在乎你研究的多深,只有人会在乎你能做出东西来,搞应用不要专研得太深。

    Java5\BoxingTest.java

    package java5;

    public class BoxingTest

    {

    public static void main(String []args)

    {

    int i=100;

    Integer iInteger=i; //装箱

    System.out.println(iInteger);

    Integer iInteger1=new Integer(200);

    int i1=iInteger1; //拆箱

    System.out.println(i1);

     

    Integer i3=-128;

    Integer i4=-128; //判断是相等的

    //-128 ~ 127 用双等号判断是相等的

    if(i3==i4)

    {

    System.out.println("Equal!");

    }

    else

    {

    System.out.println("No Equal!");

    }

    }

    }

     

    2.增强的for循环

    Java5\ ForTest.java

    package java5;

    import java.util.*;

    public class ForTest

    {

    public static void main(String []args)

    {

    List list=new ArrayList();

    list.add("abc");

    list.add("xyz");

    list.add("test");

    for(Object obj:list) //遍历list

    {

    String string=(String)obj;

    System.out.println(string);

    }

    String []strings=new String []{"core java","sql","xml","hibernate"};

    System.out.println("-------------------------------");

    for(String str:strings) //遍历数组

    {

    System.err.println(str);

    }

    System.out.println("-------------------------------");

    Set set=new HashSet(); //遍历Set

    set.add("set1");

    set.add("set2");

    set.add("set3");

    for(Object obj:set)

    {

    String string=(String)obj;

    System.out.println(string);

    }

    System.out.println("-------------------------------");

    Map map=new HashMap(); //遍历Map

    map.put(1,"map1");

    map.put(2,"map2");

    map.put(3,"map3");

    for(Object obj:map.entrySet())

    {

    Map.Entry entry=(Map.Entry)obj;

    System.out.println(entry.getKey()+"=>"+entry.getValue());

    }

    }

    }

     

    3.System.out.printf();

    //标准格式化输出 类似C

    printf("%d",100);

    printf("%s","test");

    java5/PrintfTest.java

    package java5;

    import java.util.*;

    public class PrintfTest

    {

    public static void main(String []args)

    {

    int i=100;

    String string="test";

    System.out.printf("%d,%s,%S \n",i,string,string);

    System.out.printf(i+","+string+","+string.toUpperCase()+"\n");

    System.out.println(i+","+string+","+string.toUpperCase());

    System.out.printf("%1$d,%2$s,%2$S,%1$d \n",i,string);

    //1$代表第一个参数,2$代表第二个参数

    //%d %s 格式符

    }

    }

     

    java.util.Formatter

    格式化日期

    2011-12-07 113134.

    Java5\ FormatterTest.java

    package java5;

    import java.util.*;

    public class FormatterTest

    {

    public static void main(String []args)

    {

    StringBuffer sb=new StringBuffer();

    StringBuffer sb2=new StringBuffer();

    StringBuffer sb3=new StringBuffer();

    Formatter formatter=new Formatter(sb);

    Formatter formatter2=new Formatter(sb2);

    Formatter formatter3=new Formatter(sb3);

    //formatter.format("%1$tY",new java.util.Date());

    //System.out.println(sb);

     

    formatter.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "

    +"\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL",new java.util.Date());

    System.out.println(sb);

     

    System.out.println("-------------------------------");

    formatter2.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "

    +"\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL",System.currentTimeMillis());

    System.out.println(sb2);

     

    System.out.println("-------------------------------");

    formatter3.format("%1$tY-%1$tm-%1$td %1$tD %1$tH:%1$tM:%1$tS "

    +"\n %1$tr \n%1$tF \n %1$tH/%1$tI:%1$tM:%1$tS.%1$tL",Calendar.getInstance());

    System.out.println(sb3);

    }

    }

     

    4.静态导入

    import static

    java5/StaticImportTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    import static java.lang.Math.*;

     

    public class StaticImportTest

    {

    public static void main(String []args)

    {

    out.println("static import test");

    out.println(PI);

    out.println(abs(-1));

    }

    }

     

    5.可变长度的参数

    add(int a,int b)

    add(int a,int b,int c)

    ......

    add(int[] a) --> add(int... args)

    java5/VarTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    public class VarTest

    {

    public static int add(int... args)

    {

    int length=args.length;

    int result=0;

    for(int i=0;i<length;i++)

    {

    result+=args[i];

    }

    out.println("args.length:"+args.length);

    return result;

    }

    public static void main(String... args)

    {

    out.println(add(1,2));

    out.println(add());

    out.println(add(100,200,300,800));

    }

    }

     

    6.泛型 Generic

    List list=new ArrayList();

    list.add("string1");

    list.add("string2");

    list.add(new Employee()); //会报ClasscastException异常

    for(Object obj:list)

    {

    String str=(String)obj;

    out.println(str);

    }

    泛型的作用:

    a.类型检查(编译期)

    List<String> list=new ArrayList<String>();

     

    java5/GenericTest.java

     

    使用泛型约束自定义方法的参数

    list.add(3.5);

    list.add(9);

    list.add("string");

    sum(list);

    public static int sum(List<Number> list)

    {

    double result=new Double(0.0f);

    }

    java5/VarTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    public class GenericTest

    {

    public static void main(String... args)

    {

    List<String> list=new ArrayList<String>();

    list.add("string1");

    list.add("string2");

    list.add((new java.util.Date()).toString());

    for(Object obj:list)

    {

    //String string=(String)obj;

    System.out.println(obj);

    }

     

    out.println("------------------------------");

    Map<String,String> map=new HashMap<String,String>();

    map.put("Hello","java");

    map.put("World","sun");

    map.put("HelloWorld","eclipse");

    for(String str:map.keySet())

    {

    out.println("key:"+str+"\tvalue:"+(String)map.get(str));

    }

     

    out.println("------------------------------");

    for(Object obj:map.entrySet())

    {

    Map.Entry entry=(Map.Entry)obj;

    System.out.println(entry.getKey()+"=>"+entry.getValue());

    }

     

    out.println("------------------------------");

    List<Number> list1=new ArrayList<Number>();

    list1.add(5.5f);

    list1.add(100);

    sum(list1);

     

    out.println("------------------------------");

    Integer[] arrayInt=new Integer[]{1,100,999};

    String[] arayString=new String[]{"str1","str2","str3"};

    print(arrayInt);

    print(arayString);

    }

     

    public static void sum(List<? extends Number> list)

    {

    Number result=new Float(0);

    for(Number num:list)

    {

    //out.println("result.floatValue:"+result.floatValue());

    //result=new Float(result.floatValue()+num.floatValue());

    //给对象赋值,new的方式,太浪费空间

    result=result.floatValue()+num.floatValue(); //自动装箱

    //out.println("result:"+result.floatValue());

    out.println("result:"+result.floatValue()); //自动拆箱

    }

    }

    //add(E element)

    public static <E> void print(E [] array) //E代表可以传入任意类型,<E> 表示声明E为任意类型

    {

    for(Object obj:array)

    {

    out.println(obj);

    }

    }

    }

     

    cvs

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

    Alpha

    Beta

     

    Release Candidate 发布候选版

    RC1

    GA General Avaibility 正式版本

     

    7.枚举

    用来替换常量 效果跟常量是相同的

    public enum Size

    {

    LARGE,MIDDLE,SAMLL

    }

    拿到Size的值

    Size.LARGE

     

    java5/EnumTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    enum Size //枚举类

    {

    //LARGE,MIDDLE,SMALL //加个封号,和不加封号都没错,最好加封号

    LARGE(50)

    {

    public String toString(){

    return "size:large value:"+this.getValue();

    }

    },

    MIDDLE(30)

    {

    public String toString(){

    return "Size:middle value:"+this.getValue();

    }

    },

    SMALL(20)

    {

    public String toString(){

    return "Size:small value:"+this.getValue();

    }

    };

     

    Size(){}

    Size(int value)

    {

    this.value=value;

    }

     

    private int value;

    public int getValue()

    {

    return this.value;

    }

    }

     

    public class EnumTest

    {

    private Size size;

    public EnumTest(Size size)

    {

    this.size=size;

    }

     

    public static void main(String... args)

    {

    EnumTest test=new EnumTest(Size.LARGE);

    out.println(test);

    }

     

    public String toString()

    {

    out.println(size.toString());

    return Arrays.deepToString(size.values());

    }

     

    }

     

    8.annotation 注解

    辅助程序运行 在注解中进行程序的配置

    port:8888 ip:localhost

    @Override :@符号开头+注解类

    主流框架产品都支持使用注解进行程序配置

    xml文件配置(文本配置)

    (xml,properties文件配置)

    将程序的数据与程序本身分离

     

    将程序的数据分离

    使用注解的配置可验证(通过编译验证)

    public String toString()

    {

    }

    java5/OverrideTest.java

     

    注解:三种

    1. Marker Annotation:标记注解

    @Override

     

    2. Single value Annotation:单值注解

    @Test(input="abc")

     

    3. Muti Value Annotation 多值注解

    @Test(input="abc",output="ABC")

     

    4. 自定义注解:类似于类

    Test.java

     

    @Retention(RetentionPolicy.CLASS)

    @Target(ElementType.METHOD)

    public @interface Test

    {

    String input();

    String output();

    }

     

    target:指定自定义的注解能够在什么地方使用

    class A

    {

    private int age;

    @Test //因为Target是被指定为METHOD

    public void setAge()

    {

     

    }

    }

     

    Retention:表示注解的生命周期

    source:只在于源代码中

    class:只存在于class文件中

     

    java5/Test.java

    package java5;

    import java.lang.annotation.*;

    @Retention(RetentionPolicy.RUNTIME)

    @Target(ElementType.METHOD)

    public @interface Test {

    String input();

    String output();

    }

     

    java5/RententionTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    import java.lang.annotation.*;

    @Retention(RetentionPolicy.RUNTIME)

    @Target(ElementType.METHOD)

    public @interface RententionTest

    {

    String input();

    String output();

    }

     

    java5/ AnnotationTest.java

    package java5;

    import java.util.*;

    import static java.lang.System.out;

    import java.lang.annotation.*;

    import java.lang.reflect.*;

    public class AnnotationTest

    {

    @RententionTest(input="ABC",output="abc")

    public static String toLowerCase(String str)

    {

    return str.toLowerCase();

    }

     

    public static void main(String args[])

    {

    Class clz=AnnotationTest.class;

    Method [] method=clz.getDeclaredMethods(); //得到类中的所有方法

    for(int i=0;i<method.length;i++)

    {

    boolean hasAnnotation=method[i].isAnnotationPresent(RententionTest.class);

    if(hasAnnotation)

    {

    RententionTest test=(RententionTest)method[i].getAnnotation(RententionTest.class); //Annotation

    String input=test.input(); //拿到Annotation的值

    String expectedOutput=test.output();

    String realOutput=toLowerCase(input);

    if(expectedOutput.equals(realOutput))

    {

    out.println("Test Successful");

    }

    else

    {

    throw new AssertionError("Test"+"failed!!!");

    }

    }

    }

    }

    }

  • 相关阅读:
    团队作业7
    团队作业五
    团队作业四
    团队作业3
    团队作业调研
    团队作业 团队组织方式讨论
    团队成员介绍
    iOS大神博客列表
    iOS JSBridge实现
    「节日换肤」通用技术方案__iOS端实现
  • 原文地址:https://www.cnblogs.com/luowei010101/p/2285487.html
Copyright © 2011-2022 走看看