码迷,mamicode.com
首页 > 其他好文 > 详细

11-泛型

时间:2017-01-18 00:43:09      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:cte   exp   tag   错误   blog   ide   string   ima   one   

一:

技术分享

注意:数据类型的安全性问题可以理解为避免了数据类型转换错误。

技术分享
 1 package com.example;
 2 //?是通配符,object是任意类型,不写类型
 3 class A<T>{
 4     private T age;
 5     private T name;
 6 
 7     public T getAge() {
 8         return age;
 9     }
10 
11     public void setAge(T age) {
12         this.age = age;
13     }
14 
15     public T getName() {
16         return name;
17     }
18 
19     public void setName(T name) {
20         this.name = name;
21     }
22 }
23 public class MyClass {
24     public static void main(String[] args){
25         A<String> a = new A<String>();
26         a.setAge("100");
27         a.setName("hello");
28         System.out.println("name is :"+ a.getName() + ",age is :"+ a.getAge());
29     }
30 }
View Code

二:通配符

技术分享

三:泛型接口

技术分享
 1 package com.example;
 2 interface a<T>{
 3     public abstract void say(T name);
 4 }
 5 
 6 class People implements a<String>{
 7 
 8     int b;
 9 
10     public int getB() {
11         return b;
12     }
13 
14     public void setB(int b) {
15         this.b = b;
16     }
17 
18     @Override
19     public void say(String name) {
20         System.out.print(this.getB()+name);
21 
22     }
23 }
24 
25 public class MyClass {
26     public static void main(String[] args){
27         People p = new People();
28         p.b = 10;
29         p.say("hello");
30     }
31 }
View Code

四:泛型方法

技术分享

 

技术分享
 1 package com.example;
 2 class A {
 3     public <T>T tell(T t){
 4         System.out.println(t);
 5         return t;
 6     };
 7 }
 8 public class MyClass {
 9     public static void main(String[] args){
10         A a = new A();
11         a.tell("hello");
12         a.tell(12);
13     }
14 }
View Code

五:泛型数组

技术分享

技术分享
 1 package com.example;
 2 
 3 public class MyClass {
 4     public static void main(String[] args){
 5         String arr[] = {"i","am","zwzx"};
 6         tell(arr);
 7     }
 8     public static  <T>void tell(T arr[]){
 9         for (int i = 0 ;i <arr.length;i++){
10             System.out.println(arr[i]);
11         }
12     }
13 }
View Code

 

11-泛型

标签:cte   exp   tag   错误   blog   ide   string   ima   one   

原文地址:http://www.cnblogs.com/BelieveFish/p/6295118.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!