Java generic class array return function notation question

Asked 2 years ago, Updated 2 years ago, 25 views

https://d2.naver.com/helloworld/1219

I'm reading this post in the middle

class ValueHolder<T>{  //generic class
    private T value;
    public ValueHolder(T value) {  
        this.value = value;   
    }
    public T getValue() {  
        return value;  
    }
}

public class ImprovedGenericEx2{

    public static <T> ValueHolder<T>[] doBadThing(ValueHolder<T>... values) { //Varargs
    // // public static <String> ValueHolder<String>[] doBadThing(ValueHolder<String>... values)

        Object[] objs = values;  
        objs[0] = new ValueHolder<Integer>(10);  
        return values;  

    }

    public static void main(String[] args) {    

        ValueHolder<String>[] result = doBadThing(new ValueHolder<String>("foo"), new ValueHolder<String>("bar"));

        for (ValueHolder<String> holder : result) {  
            String value = holder.getValue(); // ClassCastException occurred  
            System.out.println(value);  
        }
    }
}

Here

public static <T> ValueHolder<T>[] doBadThing(ValueHolder<T>... values)

<T> Why do you need?

java

2022-09-22 19:48

1 Answers

It's called the generic method.

Method with type parameters of medium type and return type. If you remove it, it is a grammar error and cannot be compiled.

public static <T> MyClass<T> createMyClass(T t)
{
    MyClass<T> myClass= new MyClass<T>();
    ...

    return myClass;
}

I searched the example and found the example below.

public class Box<T> {
private T t;

public T getT() {
    return t;
}

public void setT(T t) {
    this.t = t;
}
}
public class Util {
public static <T> Box<T> boxing(T t)
{
    Box<T> box = new Box<T>();

    box.setT(t);

    return box;
}
}
public class Main {
public static void main(String[] args) {
    Box<Integer> box1 = Util.<Integer>boxing (100); // Look at the type here. The generic type of the boxing method is Integer.
    int intValue = box1.getT();

    Box<String> box2 = Util.<String>boxing("ABC"); // General type is String
    String strValue = box2.getT();
}
}


2022-09-22 19:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.