Java教程

java001-泛型

本文主要是介绍java001-泛型,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

泛型出现的意义:

为编码阶段的不确定性和转化做视觉设计

将运行期遇到的问题转移到编译期,省去了强转的麻烦

package com.xiaolin.basic;

/**
 * 泛型:将运行期遇到的问题转移到了编译期,省去了强转的麻烦
 * val1,val2
 *  @author: xiaolin
 *  @Date: 2021/6/11 22:49
 *  @Description:
 */
public class LocalPair<K,V> {
    private K k;
    private V v;

    public LocalPair(K k, V v) {
        this.k = k;
        this.v = v;
    }


    public K getK() {
        return k;
    }

    public V getV() {
        return v;
    }
}

 

package com.xiaolin.basic;

import java.util.Date;

public class LocalPairApp {
    public static void main(String[] args) {
        LocalPair<String,String> pair = foo1();

        String k = pair.getK();
        String v = pair.getV();

        String[] arrs = k.split(",");
        String[] arrs2 = v.split(",");

        for (String s:arrs){
            System.out.println(s);
        }

        for (String b:arrs2){
            System.out.println(b);
        }
    }


    public static LocalPair<String,String> foo1(){
        LocalPair<String,String> pair1 = new LocalPair<>("abc,rer","bcd,oiu");

        return pair1;
    }


    public static LocalPair<String,Integer> foo2(){
        LocalPair<String,Integer> pair2 = new LocalPair<>("bdsd",123);

        return pair2;
    }


    public static LocalPair<String, Date> foo3(){
        LocalPair<String,Date> pair3 = new LocalPair<>("bdsd",new Date());

        return pair3;
    }
}

  

  

这篇关于java001-泛型的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!