[java] The difference between generics and Objects, how to choose generics and Objects in actual scenarios

Introduction

This article introduces the difference between generics and Objects, how to choose generics and Objects in actual scenarios

what is generic

The following content is from the rookie tutorial:

Java generics (generics) is a new feature introduced in JDK 5. Generics provide a compile-time type safety detection mechanism that allows programmers to detect illegal types at compile time.

The essence of generics is a parameterized type, which means that the type of data being manipulated is specified as a parameter.

Suppose we have such a requirement: write a sorting method that can sort integer arrays, string arrays or even any other type of array, how to achieve it?

The answer is that you can use Java generics.
Using the concept of Java generics, we can write a generic method to sort an array of objects. Then, call this generic method to sort an array of integers, arrays of floats, arrays of strings, and so on.

Generic markers in java:

E - Element (used in collections because elements are stored in collections)
T - Type (Java class)
K - Key (key)
V - Value (value)
N - Number (numeric type)
? - Indicates an indeterminate java type

In fact, AZ can be used as a generic marker. The above is just a convention to enhance the readability of the code and facilitate the cooperative development between teams.

The role of generics

  1. Advance errors that occur at runtime to compile time

  2. Avoid the trouble of type coercion

What is the difference between generics and the Object class

Mainly the timing of use is different

  • Generics: If I determine which object to use and use the properties in this object, I choose to use generics, because generics represent more precise objects and can use unique methods.

  • Object class: Object is the parent class of all classes, which is very general and can only use fixed attributes. As long as there is an Object, it can basically be replaced by generics.

How to choose generics in actual scenarios

Case 1. Create a generic class

In fact, this example is very common. There are many cases in the java source code, such as some common collection classes

insert image description here

Because java does not know the type we want to pass in when it is used by developers, and if you use Object, you need to force it yourself, and type conversion exceptions may occur

Case 2. Use generics to define tool classes (solve cache penetration)

In the same way, if we want to customize the tool class for others to use, we must use generics, because we are not sure what types the user wants to pass in.

/**
     * 缓存穿透
     * @param keyPrefix key的前缀
     * @param id    id
     * @param type  返回值类型
     * @param dbFallback    函数
     * @param time  时间
     * @param unit  单位
     * @return
     * @param <T>   类型的泛型
     * @param <ID>  id的泛型
     */
    public <T,ID> T queryWithPassThrough(String keyPrefix, ID id , Class<T> type, Function<ID, T> dbFallback, Long time, TimeUnit unit){
    
    
        String key = keyPrefix + id;
        // 1.从redis查询商铺缓存(以string类型为例)
        String json = stringRedisTemplate.opsForValue().get(key);
        // 2.判断是否存在
        if(StrUtil.isNotBlank(json)){
    
    
            // 3.存在,直接返回
            return JSONUtil.toBean(json, type);
        }

        // 判断命中的是否是空值
        if (json != null){
    
    
            return null;
        }

        // 4.不存在,根据id查询数据库
        T t = dbFallback.apply(id);

        // 5.不存在,返回错误
        if (r == null){
    
    
            // 将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }

        // 6.存在,写入redis
        this.set(key, t, time, unit);

        // 7.返回
        return t;
    }

Case 3. The collection class uses the indeterminate generic type "<?>"

Here you need to use indeterminate generics to receive collection classes

    public String export(ArrayList<?> arrayList, Class<?> excelVO, String sheetName) {
    
    
        String fileName = System.currentTimeMillis() + XLSX;
        EasyExcel.write(fileName, excelVO).sheet(sheetName).doWrite(arrayList);
        return fileName;
    }

Guess you like

Origin blog.csdn.net/qq_51383106/article/details/131783620