范型extends和super以及序列化transient关键字记录

1. 范型通配符中,当使用如List<? extends Basic>这种方式做为范型参数时,表示不知道具体持有什么类型,因此在使用java

List<? extends Map> a = new ArrayList<HashMap>();
        //compile error
        //a.add(new HashMap<String, String>());

这种执行添加元素会编译错误,可是能够执行get操做, 觉得get时已经编译器已经认为存放的数据是基于Basic类型的,可是添加时不知道具体添加的会是什么类型,认为是不安全的因此不能添加。而List <? super T>用于方法参数中,这样表示是一个具体的参数类型,认为添加的参数类型只要是继承自T的就能够,编译器认为add是安全的。安全

2.transient序列化关键字this

import com.sun.tools.corba.se.idl.StringGen;

import java.io.*;
import java.lang.ref.*;
import java.util.*;


public class NesttyMain implements Serializable{

    private Date date = new Date();
    private String userName;
    private transient String password;

    public NesttyMain(String userName,String password){
        this.userName = userName;
        this.password = password;
    }

    public String toString(){
        return "username: "+userName+" \n password: "+password + "\n date: "+ date;
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        NesttyMain a = new NesttyMain("cqq","123");
        System.out.println("a = "+a);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("nestty.out"));
        out.writeObject(a);
        out.close();
        Thread.sleep(1000);
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("nestty.out"));
        a = (NesttyMain) in.readObject();
        System.out.println("a = "+a);
    }

}

输出:code

执行序列化以后再读取,transient修饰的密码字段不会打印出来继承

相关文章
相关标签/搜索