• 泛型


    package cn.hncu.generic.v1;

    import java.util.ArrayList;
    import java.util.Iterator;

    public class GenericDemo1 {
    public static void main(String[] args) {
    ArrayList list = new ArrayList();
    list.add("a111");
    list.add("a222e23");
    list.add("a333fdjk23232");
    list.add(100);//这一句会导致出现异常

    Iterator it = list.iterator();
    while(it.hasNext()){
    String str = (String) it.next();
    System.out.println(str+"---,len:"+str.length());
    }
    }
    }

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

    package cn.hncu.generic.v1;

    import java.util.ArrayList;
    import java.util.Iterator;

    public class GenericDemo2 {
    public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    //ArrayList<Integer> list = new ArrayList<Integer>();

    list.add("a111");
    list.add("a222e23");
    list.add("a333fdjk23232");
    //list.add(100);//泛型的第1个好处:可以把运行期的错误提前到编译期

    Iterator<String> it = list.iterator();
    while(it.hasNext()){
    String str = it.next(); //泛型的第2个好处:不需要类型强转
    System.out.println(str+"---,len:"+str.length());
    }
    }
    }

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

    package cn.hncu.generic.v1;

    public class MySet<E> {
    private E objs[];

    @SuppressWarnings("unchecked")
    public MySet() {
    Object t[] = new Object[0];
    objs =(E[])t;
    }

    @SuppressWarnings("unchecked")
    public boolean add(E obj) {
    // 判断对象是否已经存在----用卫条件守护
    if( contains(obj) ){
    return false;
    }

    // 扩容
    Object tempObjs[] = new Object[objs.length + 1];
    for (int i = 0; i < objs.length; i++) {
    tempObjs[i] = objs[i];
    }
    tempObjs[objs.length] = obj;
    objs = (E[]) tempObjs;

    return true;
    }

    public boolean contains(Object obj){
    for(Object o:objs){
    if(o.equals(obj)){
    return true;
    }
    }
    return false;
    }

    public E[] getAll(){
    return objs;
    }

    public int size() {
    return objs.length;
    }

    }

  • 相关阅读:
    C# 多线程 弹出模态MessageBox的一种方法
    CentOS 7安装Docker
    CentOS 6 安装Docker
    docker三要素
    openstack_dashboard无法获取nova
    cinder安装与配置
    Dashboard安装与配置
    openstack-neutron安装与配置
    openstack在controller节点使用openstack network agent list不显示计算节点
    nova安装与配置
  • 原文地址:https://www.cnblogs.com/1314wamm/p/5677080.html
Copyright © 2020-2023  润新知