1.关于泛型
集合中可以放任意对象,把对象存于集合中,他们就会提升为Object类型。当我们在取用时就需要进行转型
public class GenericDemo {
public static void main(String[] args) {
//一般在创建对象时,将未知的类型确定具体的类型。当没有指定泛型时,默认类型为Object类型。
Collection coll = new ArrayList();
coll.add("abc");
coll.add("itcast");
coll.add(5);//由于集合没有做任何限定,任何类型都可以给其中存放
Iterator it = coll.iterator();
while(it.hasNext()){
//需要打印每个字符串的长度,就要把迭代出来的对象转成String类型
String str = (String) it.next();
System.out.println(str.length());
}
}
}//在此处就会出现运行时异常。
原因是存储时类型转换成了Object在取用时需要强转引发类转换异常ClassCastException.
在使用泛型后:
public class Demo2 {
public static void main(String[] args) {
//我们在创建集合对象时加上<String>泛型在取用时就是string类型的数据。
Collection<String> list = new ArrayList<String>();
list.add("abc");
list.add("itcast");
// list.add(5);//当集合明确类型后,存放类型不一致就会编译报错
// 集合已经明确具体存放的元素类型,那么在使用迭代器的时候,迭代器也同样会知道具体遍历元素类型
Iterator<String> it = list.iterator();
while(it.hasNext()){
String str = it.next();
//当使用Iterator<String>控制元素类型后,就不需要强转了。获取到的元素直接就是String类型
System.out.println(str.length());
}
}
}//此时不会出现问题
泛型的定义
定义和使用含有泛型的类:
修饰符 class 类名<代表泛型的变量> { }
class ArrayList<E>{
public boolean add(E e){ }
public E get(int index){ }
....
}
在创建对象的时候确定泛型
例如:
Panda<Object> panda = new Panda<>();
ArrayList<String> list = new ArrayList<String>();
class ArrayList<String>{
public boolean add(String e){ }
public String get(int index){ }
...
}
class ArrayList<Integer> {
public boolean add(Integer e) { }
public Integer get(int index) { }
...
}
继承的抽象类有泛型则子类也需要加泛型
含有泛型的方法:
修饰符 <代表泛型的变量> 返回值类型 方法名(参数){ }
并不是所有的方法都适合使用泛型
使用泛型的方法带有参数才有意义,无参的都是无意义的。
:注意:带有参数的T返回值类型与参数列表的T类型一样。
当前类有泛型时,成员方法不要加。(就是想要方法的泛型与类的泛型一直。)
使用格式:调用方法时,确定泛型
class Dog{
public <T> void test(T t){
System.out.println("t");
}
}
public class Demo{
public static void main(String[] args){
Dog dog = new Dog();
dog.test("name");//此时T就是String
dog.test(28);//此时T是 Int 类型
}
} //在使用时会确定泛型。
含有泛型的接口:
修饰符 interface接口名<代表泛型的变量> { }
public interface Myinter<T>{
void show(T t);
}
//使用时
public class MyImpl implements Myinter<String>{
public void show(String t){
System.out.println(t);
}
}
带有泛型的抽象类:
//抽象类,暂时没有办法直接实例化,只能再写一个普通类去继承抽象类
//总结:继承了带有泛型的抽象类,那么继承类也需要有泛型!!!
包装类(八大基本数据类型)
/**
* int 的包装类 Integer
* byte 的包装类 Byte
* short 的包装类 Short
* long 的包装类 Long
* float 的包装类 Float
* double 的包装类 Double
* char 的包装类 Character
* boolean 的包装类 Boolean
*
*/