欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java中泛型使用实例详解

程序员文章站 2024-02-23 18:09:28
java中泛型使用 泛型作用: 泛型:集合类添加对象不用强转 反射机制:将泛型固定的类的所有方法和成员全部显示出来  核心代码: a...

java中泛型使用

泛型作用:

泛型:集合类添加对象不用强转

反射机制:将泛型固定的类的所有方法和成员全部显示出来 

核心代码:

arraylist<ls> ff=new arraylist()<ls>;

ls ls1=new ls("薯片",5f);

ff.add(ls1);

ls cls=ff.get(0);//这里不再需要强转

 

 

代码实例:

说明:这是非泛型的代码,集合类中调用对象时需要强转

import java.util.*;

public class l4_6

{

  public static void main(string[] args)

  {

          //hashtable ff=new hashtable();       

       arraylist ff=new arraylist();

       ls ls1=new ls("薯片",5f);

       ff.add(ls1);

     ls cls=(ls)ff.get(0);

       yl hyl=(yl)ff.get(0);//这样显然是不对的

     }

}

class ls

{

  private string mingcheng;

  private float jiage;

 

  ls(string mingcheng,float jiage)

  {

      this.mingcheng=mingcheng;

      this.jiage=jiage;

  }

}

class yl

{

  private string mingcheng;

  private float jiage;

  private string yanse;

 

  yl(string mingcheng,float jiage,string yanse)

  {

      this.mingcheng=mingcheng;

      this.jiage=jiage;

      this.yanse=yanse;

  }

}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!