泛型

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Generic {
 public static void main(String[] args) {
  HashMap<String,Integer> maps= new HashMap<String,Integer>();
  maps.put("zhangsan", 20);
  maps.put("lisi", 30);
  maps.put("wangwu", 25);
  //不能直接对Map进行迭代,因为Map没有实现Iterable(可迭代)接口,只能用Set<Map.Entry<K,V>>迭代
  System.out.println(maps);
  //Map.Entry能成对取出key和value的值
  Set<Map.Entry<String, Integer>> entrySet= maps.entrySet();
  //遍历分别取出key和vablue的值
  for(Map.Entry<String, Integer>entry:entrySet){
   System.out.println(entry.getKey()+":"+entry.getValue());
  }
  add(3,5);
  Number x =add(3,3.5);
//  System.out.println(x);
//  交换1和2的位置
  swap(new String[]{"abc","def","ddf"},1,2);
/**  只有引用类型才能作为泛型方法的实际参数,对于add方法,使用基础类型的测试没问题,这是因为自动装箱和
 * 拆箱了。swap(new int[]{1,2,3,4},2,3)会报错,因为new int[]{1,2,3,4}本身已经是对象了,你想要的有
 * 可能就是int数组呢?那它装箱岂不是弄巧成拙
 *  swap(new int[]{1,2,3,4},2,3);
 */ //
  Object obj = "xyz";
  String a = autoConvert(obj);
 }
 private static <T> T add(T x,T y){
  return null;
 }
 private static <T> void swap(T[] a,int i, int j){
  T temp = a[i];
  a[i] = a[j];
  a[j] = temp;
 }
 private static <T>T autoConvert(Object obj){
  return (T)obj;
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值