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

How to use t in java

Release: 2019-12-28 10:04:46
Original
3980 people have browsed it

How to use t in java

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 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);
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template