泛型

来源:互联网 发布:js当前时间加一小时 编辑:程序博客网 时间:2024/05/15 23:56

1、泛型可以解决数据类型的安全问题,他主要的原理,是在类声明的时候通过一个标识表示类中某个属性的类型或者是某个方法的返回值及参数类型。

格式:

2、访问权限 class 类名称<泛型,泛型…> {

         属性

         方法

}

3、对象的创建

         类名称<具体类型> 对象名称 = new 类名称<具体类型>();

package test;//一般表示泛型用大写的Tclass Point<T> {private T x;private T y;public T getX() {return x;}public void setX(T x) {this.x = x;}public T getY() {return y;}public void setY(T y) {this.y = y;}}public class Demo {public static void main(String[] args) {Point<String> p = new Point<String>();p.setX("精度为:109");p.setY("维度:108");System.out.println(p.getX() + " " + p.getY());}}

构造方法中使用泛型:

<pre name="code" class="html">package test;
class ConS<T> {private T value;public ConS(T value) {this.value = value;}public T getValue() {return value;}public void setValue(T value) {this.value = value;}}public class Demo {public static void main(String[] args) {ConS<String> c = new ConS<String>("构造方法中使用泛型");System.out.println(c.getValue());}}

使用多个泛型:

package test;class Genr<K, T> {private T take;private K key;public Genr(K key, T take) {this.key = key;this.take = take;}public T getTake() {return take;}public void setTake(T take) {this.take = take;}public K getKey() {return key;}public void setKey(K key) {this.key = key;}}public class Demo {public static void main(String[] args) {Genr<String, Integer> g = new Genr<String, Integer>("使用多个泛型", 1);System.out.println(g.getKey());}}

通配符的使用:

package test;class Info<T> {private T value;public T getValue() {return value;}public void setValue(T value) {this.value = value;}}public class Demo {public static void main(String[] args) {Info<String> i = new Info<String>();i.setValue("通配符的使用");tell(i);}//可使用Info,但不可使用Info<Object>,会根据类的class判断,一旦指定了泛型,就必须是指定的类型,其父类型也不可public static void tell(Info<?> i) {System.out.println(i.getValue());}}

使用泛型接口:

package test;interface GenInter<T>{public void say();}//实现类也可以指定具体类型,如Gin<String>class Gin<T> implements GenInter<T> {private T info;public Gin(T info) {this.info = info;}public T getInfo() {return info;}@Overridepublic void say() {System.out.println(info);}}public class Demo {public static void main(String[] args) {Gin<Integer> i = new Gin<Integer>(2);i.say();}}

泛型方法的使用:

package test;class Gener {public <T>T tell(T t) {return t;}}public class Demo {public static void main(String[] args) {Gener g = new Gener();System.out.println(g.tell("泛型方法的使用"));}}

泛型数组的使用:

package test;public class Demo {public static void main(String[] args) {Integer[] arr = {1, 2, 3};tell(arr);}public static <T>void tell(T arr[]) {for (int i = 0; i < arr.length; i++) {System.out.println(arr[i]);}}}





0 0
原创粉丝点击