泛型和异常

一泛型

  1,动态数组扩容

  代码:Myarray能够存储任意类型的数据,缺点是取出时不知原本是什么类型

   public class Myarray {

   private Object[] datas;

    private int count = 0;

public Myarray() {
datas = new Object[10];
}
public void put(Object object) {
datas[count] = object;
count++;
if(count == datas.length){
Object[] newArr = new Object[datas.length*2];
for (int i = 0; i < datas.length; i++) {
newArr[i]=datas[i];
}
datas = newArr;
}
}
public Object get(int index) {
return datas[index];
}
public void remove(int index) {
}
public int size(){
return count;
}
}

二,泛型
  1,可以用在类上和方法上
  2,类:在类名后 <任意字母> 如 class Foo<T> {}
  3,命名规范:同类名,首字母大写,驼峰结构,可以使用一个字母,通常用T
  4,如果需要多个泛型,<A,B>这种形式
  5,如果没有指定泛型,则默认为Object
三,异常exception
  1,异常分为RuntimeException(运行时异常)和FileNoFoundException
  2,try-catch代码块可以捕获异常,并且程序不会停止运行,执行catch内的代码块
  3,所有的异常可以通过throw抛出 throw+异常对象
  4,自定义异常需要继承父类异常
五,动态数组ArrayList
  常用用法: ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("hello");//放入元素
        arrayList.add(0,"hello");//把元素插入指定位置
        arrayList.remove(1);//删除指定位置元素
        arrayList.set(0,"你好");//更改指定位置元素
        arrayList.get[1];//取出索引位置为1的元素
  增强for循环
    ArrayList继承父类Iterable可以使用增强for循环
    for(String s1 : arrayList){}

    

 

posted on 2018-04-11 20:02  北冥丶中郎将  阅读(150)  评论(0编辑  收藏  举报