zoukankan      html  css  js  c++  java
  • java泛型

    先举一个利用泛型的简单例子

        public static void main(String[] args)
        {
            //一般方式
    //        List list = new ArrayList();
    //        
    //        list.add("Forever");
    //        list.add("Love");
    //        list.add(110);
            
            //泛型方式
            List<String> list=new ArrayList<>();
            list.add("Water");
            list.add("Stone");
            list.add(123);
            
    
            for(int i=0;i<list.size();i++)
            {
                String name=(String)list.get(i);
                System.out.println("name:"+name);
            }
        }

    在List集合中,可以存放很多的数据类型,包括整型和字符串类型,因为其是一个Object类型,但是很多时候在取数据时,忘记了之前存储的数据类型,而会出现报错,

    其实我个人理解,泛型更多的作用是保护数据的安全性,先定义了数据的类型,还有一个作用是减少一些装箱和拆箱操作,使得运行速率加快。

    泛型其实大体可以为了3类,泛型类,泛型方法,泛型接口,上面举例其实是内置的List泛型类,我们也可以自定义泛型类。

    //泛型类
    public class GenTest<K,V> {
        
        public Hashtable<K, V> h=new Hashtable<K,V>();
        
        public void put(K k,V v)
        {
            h.put(k, v);
        }
        //泛型方法,第一次返回整型,第二次返回浮点型
        public V get(K k)
        {
            return h.get(k);
        }
    
        public static void main(String args[])
        {
            //第一次实例化类型参数
            GenTest<String , Integer> obj=new GenTest<String , Integer>();
            obj.put("Messi", 30);
            int age1=obj.get("Messi");
            System.out.println("梅老板:"+age1);
            
            //第二次实例化类型参数,泛型类增加了灵活性
            GenTest<Double, Integer> obj2=new GenTest<Double,Integer>();
            obj2.put(3.14, 21);
            int age2=obj2.get(3.14);
            System.out.println("3.14:"+age2);
        }
    }

    学了忘,忘了又学,怎么回事,小老弟!

  • 相关阅读:
    codeforces C. No to Palindromes!
    codeforces D. Pashmak and Parmida's problem
    codeforces C. Little Pony and Expected Maximum
    codeforces D. Count Good Substrings
    codeforces C. Jzzhu and Chocolate
    codeforces C. DZY Loves Sequences
    codeforces D. Multiplication Table
    codeforces C. Painting Fence
    hdu 5067 Harry And Dig Machine
    POJ 1159 Palindrome
  • 原文地址:https://www.cnblogs.com/Optimism/p/10478246.html
Copyright © 2011-2022 走看看