泛型
来源:互联网 发布:北控集团工资待遇知乎 编辑:程序博客网 时间:2024/06/02 03:17
泛型有三大类:1.泛型类 2.泛型接口 3.泛型方法
泛型类
public class Container<K, V> { private K key; private V value; public Container(K k, V v) { key = k; value = v; } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; }}
public class Main { public static void main(String[] args) { Container<String, String> c1 = new Container<String, String>("name", "findingsea"); Container<String, Integer> c2 = new Container<String, Integer>("age", 24); Container<Double, Double> c3 = new Container<Double, Double>(1.1, 2.2); System.out.println(c1.getKey() + " : " + c1.getValue()); System.out.println(c2.getKey() + " : " + c2.getValue()); System.out.println(c3.getKey() + " : " + c3.getValue()); }}
name : findingseaage : 241.1 : 2.2
泛型接口
public interface Generator<T> { public T next();}
public class FruitGenerator implements Generator<String> { private String[] fruits = new String[]{"Apple", "Banana", "Pear"}; @Override public String next() { Random rand = new Random(); return fruits[rand.nextInt(3)]; }}
public class Main { public static void main(String[] args) { FruitGenerator generator = new FruitGenerator(); System.out.println(generator.next()); System.out.println(generator.next()); System.out.println(generator.next()); System.out.println(generator.next()); }}
BananaBananaPearBanana
泛型方法
public class Main { public static <T> void out(T t) { System.out.println(t); } public static void main(String[] args) { out("findingsea"); out(123); out(11.11); out(true); }}
public class Main { public static <T> void out(T... args) { for (T t : args) { System.out.println(t); } } public static void main(String[] args) { out("findingsea", 123, 11.11, true); }}
0 0
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 泛型
- 微信开放平台开发——网页微信扫码登录(OAuth2.0)
- 171. Excel Sheet Column Number--LeetCode Record
- STL<algorithm>中的nth_element()方法的使用
- HBase运行模式:单机和分布式
- 【那些工作中遇到的小问题】读写锁
- 泛型
- PHP学习 Class one
- python 去除大文件所有行全为零,所有列全为零的行和列
- navicat for mysql
- 基于springmvc的异常处理
- 酷夏解暑神果——你造吗
- 数据库交互ActiveRecord
- android 之@+id与@id以及引用中用@+id/的原因
- 考古界共识:秦始皇陵地宫不能挖