gpt4 book ai didi

java - 泛型与对象和通配符的区别

转载 作者:行者123 更新时间:2023-11-30 10:59:09 24 4
gpt4 key购买 nike

目前我正在学习泛型编程。我不明白为什么Generic Born。当我们有 Object Class(data Type) 时。代码下方,functioF1function21 我都通过了 HashCodeclass1 作为参数。两者都需要将传递的参数转换为特定的类,并且操作的输出将相同。那为什么会出现 Generic?

package know.generic;

import knowl.collection.hashcodeInternal.HashCodeclass1;

public class ClassGeneric {
public <T> void functioF1(T arg) {
System.out.println(arg.getClass().getName());
System.out.println("val1 " + arg);
HashCodeclass1 hCC = (HashCodeclass1) arg;
}

public void functioF21(Object arg) {
System.out.println(arg.getClass().getName());
System.out.println("val2 " + arg);
HashCodeclass1 hCC = (HashCodeclass1) arg;
}
}

public class TestGeneric {
public static void main(String arg[]) {
ClassGeneric cg = new ClassGeneric();
cg.functioF1(new HashCodeclass1());
cg.functioF21(new HashCodeclass1());
}
}

最佳答案

引用javadocs同样。来自网站的一些相关文本:-

Code that uses generics has many benefits over non-generic code:

1.Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

2.Elimination of casts. The following code snippet without generics requires casting: List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); When re-written to use generics, the code does not require casting: List list = new ArrayList(); list.add("hello"); String s = list.get(0); // no cast

3.Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

如果您的集合正在通过多个类传递,那么消除类型转换和类型确实很重要。它避免了意外的类转换问题,并提供了更好的可维护性。

关于java - 泛型与对象和通配符的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002994/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com