Java泛型基础

Posted 11biscuits

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java泛型基础相关的知识,希望对你有一定的参考价值。

Main.java

package 泛型;

public class Main {
    public static void main(String[]argv){
        var list=new GenericList<Integer>();
        list.add(Integer.valueOf(2));
        list.add(6);
        System.out.println(list.get(1));
        var user1=new User(10);
        var user2=new User(20);
        System.out.println(max(user1,user2));
        print(1,2);
        /*泛型与继承*/
        User user=new Instructor(666);
        printUser(user);
        var users=new GenericList<Instructor>();
        //ERROR
        //printUsers(users);
        //GenericList<Instructor> 并不能转换为 GenericList<User>
        /*Wildcards通配符解决,泛型继承问题
        * */
        printGenericListALL(users);
    }
    public static <T extends Comparable<T>> T max(T first,T second){
        return first.compareTo(second)<0?second:first;
    }
    public static <K,V> void print(K key,V value){
        System.out.println("key="+key+" value="+value);
    }
    /*泛型与继承
    *Generic Classes and Inheritance
    * */
    public static void printUser(User user){
        System.out.println(user);
    }
    public static void printUsers(GenericList<User> users){

    }
    public static void printGenericListALL(GenericList<?> users){
        //Object x=users.get(0);
    }
}

User.java

package 泛型;

public class User implements Comparable<User>{
    private int point;
    public User(int point){
        this.point=point;
    }
    @Override
    public int compareTo(User o) {
        //this < o ->-1
        //this==o  ->0
        //this > o  ->1
        return  point-o.point;
    }
    @Override
    public String toString(){
        return "point="+this.point;
    }

}

KeyValuePair.java

package 泛型;

public class KeyValuePair<K,V> {
    private K key;
    private V value;
    public KeyValuePair(K key,V value){
        this.key=key;
        this.value=value;
    }
}

Instructor.java

package 泛型;

public class Instructor extends User{
    public Instructor(int point){
        super(point);
    }
}

GenericList.java

package 泛型;

/*1、泛型什么样子
* */
public class GenericList<T> {
//public class GenericList<T extends Comparable>
//public class GenericList<T extends Comparable & Cloneable>
//public class GenericList<T extends Number> {
    private T[] items=(T[])new Object[10];
    private int count=0;
    public void add(T item){
        items[count++]=item;
    }
    public T get(int index){
        return items[index];
    }
}

以上是关于Java泛型基础的主要内容,如果未能解决你的问题,请参考以下文章

JAVA基础之“泛型”

学习笔记Java基础知识——泛型与集合

一个小栗子聊聊JAVA泛型基础

Java基础:泛型

Java基础总结泛型

java基础--泛型