Home  >  Article  >  Java  >  How to use t in java

How to use t in java

尚
Original
2019-12-28 10:04:463863browse

How to use t in java

8742468051c85b06f0a0af9e3e506b5c T means that the return value is a generic type. Whatever you pass will return the type of data, and a single T means to limit the parameter type you pass. In this case In , through a generic return method, the first data in each collection is obtained, which is achieved by returning the value 8742468051c85b06f0a0af9e3e506b5c T and T two methods.

T Usage

Return value, write T directly to indicate the type of restricted parameter. This method is generally used to jointly operate a class object, and then obtain the collection information inside Something like that.

package com.yellowcong.test;

import java.util.ArrayList;
import java.util.List;

public class Demo2<T> {

    public static void main(String[] args) {

        //限制T 为String 类型
        Demo2<String> demo = new Demo2<String>();

        //获取string类型
        List<String> array = new ArrayList<String>();
        array.add("test");
        array.add("doub");
        String str = demo.getListFisrt(array);
        System.out.println(str);

        //获取Integer类型 T 为Integer类型
        Demo2<Integer> demo2 = new Demo2<Integer>();
        List<Integer> nums = new ArrayList<Integer>();
        nums.add(12);
        nums.add(13);
        Integer num = demo2.getListFisrt(nums);
        System.out.println(num);
    }

    /**
     * 这个只能传递T类型的数据
     * 返回值 就是Demo<T> 实例化传递的对象类型
     * @param data
     * @return
     */
    private T getListFisrt(List<T> data) {
        if (data == null || data.size() == 0) {
            return null;
        }
        return data.get(0);
    }
}

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of How to use t in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn