21天精通java基础之Day14泛型

来源:互联网 发布:人才系统java源码 编辑:程序博客网 时间:2024/04/29 07:54

Day14:泛型

  不使用泛型的危害:

1.不使用泛型,任何Object及其子类的对象都可以添加进来。

2.强转为int型时,可能报ClassCastException的异常。

 泛型的使用:

1.在集合中使用:

@Testpublic void test(){List<Integer> list=new ArrayList<Integer>();list.add(88);list.add(98);Iterator<Integer> iterator = list.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}}public void test2(){Map<String, Integer> m1 = new HashMap<String,Integer>();m1.put("ss", 78);m1.put("BB", 33);m1.put("BS", 34);Set<Map.Entry<String, Integer>> set = m1.entrySet();for(Map.Entry<String, Integer> o:set){System.out.println(o.getKey() + "---" + o.getValue());}}


2.自定义泛型类、泛型接口、泛型方法:

当实例化泛型类的对象时,指明泛型的类型。指明以后,对应的类所有使用泛型的位置,都变为实例化中指定的泛型的类型。

②如果自定义了泛型类,但是在实例化时没有使用,那么默认类型就是Object。

3.泛型与继承的关系:

①继承泛型类或泛型接口时,可以指明泛型的类型。

②若A是类B的子类,那么List<A>就不是List<B>的子接口。

4.通配符:?

List<A>、List<B>...都是List<?>的子类。

? extends A :可以存放A及其子类。

? super A:可以存放A及其父类。

@Testpublic void test4(){List<String> list = new ArrayList<>();list.add("AA");list.add("BB");List<?> list1 = new ArrayList<>();list1 = list;//可以读取声明为通配符的集合类的对象Iterator<?> iterator = list1.iterator();while(iterator.hasNext()){System.out.println(iterator.next());}//不允许向声明为通配符的集合类中写入对象,只能存null//list1.add("cc");//list1.add(123);}



对于泛型类:

①静态方法中不能使用类的泛型。

②如果泛型类一个接口或者抽象类,则不能创建类的对象。

③不能在catch中使用泛型。

④从泛型类派生子类,泛型类型需要具体化。

0 0