JAVA泛型
Posted 林先森_007
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA泛型相关的知识,希望对你有一定的参考价值。
当集合中存储的对象类型不同时,那么会导致程序在运行的时候的转型异常
1 package cn.nn; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 public class Generic_test { 7 8 public static void main(String[] args) { 9 ArrayList arr = new ArrayList(); 10 arr.add(new Tiger("华南虎")); 11 arr.add(new Tiger("东北虎")); 12 arr.add(new Sheep("喜羊羊")); 13 14 System.out.println(arr); 15 16 17 Iterator it = arr.iterator(); 18 while (it.hasNext()) { 19 Tiger nextObject = (Tiger)it.next(); 20 Tiger tiger = nextObject; 21 tiger.eat(); 22 23 } 24 25 } 26 } 27 28 class Tiger { 29 String name; 30 31 public Tiger() { 32 33 } 34 35 public Tiger(String name) { 36 this.name = name; 37 } 38 39 public String toString() { 40 return "Tiger@name:" + this.name; 41 } 42 43 public void eat() { 44 System.out.println(this.name + "吃羊"); 45 } 46 47 } 48 49 class Sheep /*extends Tiger*/{ 50 String name; 51 52 public Sheep() { 53 54 } 55 56 public Sheep(String name) { 57 this.name = name; 58 } 59 60 public String toString() { 61 return "Sheep@name:" + this.name; 62 } 63 public void eat() { 64 System.out.println(this.name + "吃青草"); 65 66 } 67 }
出现 Exception in thread "main" java.lang.ClassCastException: cn.nn.Sheep cannot be cast to cn.nn.Tiger at cn.nn.Generic_test.main(Generic_test.java:19)错误。
1 package cn.nn; 2 3 import java.util.ArrayList; 4 import java.util.Iterator; 5 6 public class Generic_test { 7 8 public static void main(String[] args) { 9 ArrayList arr = new ArrayList(); 10 arr.add(new Tiger("华南虎")); 11 arr.add(new Tiger("东北虎")); 12 arr.add(new Sheep("喜羊羊")); 13 14 System.out.println(arr); 15 16 17 Iterator it = arr.iterator(); 18 while (it.hasNext()) { 19 Tiger nextObject = (Tiger)it.next(); 20 Tiger tiger = nextObject; 21 tiger.eat(); 22 23 } 24 25 } 26 } 27 28 class Tiger { 29 String name; 30 31 public Tiger() { 32 33 } 34 35 public Tiger(String name) { 36 this.name = name; 37 } 38 39 public String toString() { 40 return "Tiger@name:" + this.name; 41 } 42 43 public void eat() { 44 System.out.println(this.name + "吃羊"); 45 } 46 47 } 48 49 class Sheep extends Tiger{ 50 String name; 51 52 public Sheep() { 53 54 } 55 56 public Sheep(String name) { 57 this.name = name; 58 } 59 60 public String toString() { 61 return "Sheep@name:" + this.name; 62 } 63 public void eat() { 64 System.out.println(this.name + "吃青草"); 65 66 } 67 }
以上是关于JAVA泛型的主要内容,如果未能解决你的问题,请参考以下文章
什么意思 在HashMap之前 ? Java中的泛型[重复]