gpt4 book ai didi

java - 在java中的通用类内部进行转换

转载 作者:行者123 更新时间:2023-12-01 07:25:59 24 4
gpt4 key购买 nike

我知道我们可以通过添加使用 java 中的泛型来跳过转换,如下所示。 (当我们在 Generic 类之外使用它时。)

但是,如果我们在泛型类 ( T item ) 内的类型对象 ( Container<T> ) 上执行一些逻辑,我们应该检查 的实例并进行特殊转换,不是吗?因此我们可以使用它来跳过泛型类的强制转换。

请查看 public void setItem(T item) 中注释的代码方法。

我想知道我的理解是否正确,还是我遗漏了什么

Client.java

    public class Client {

public static void main(String[] args) {


// String container
Container<String> stringContainer = new Container<String>();
stringContainer.setItem("Test");
//stringContainer.setItem(new StringBuffer("")); // compilation error, type safety checking

System.out.println(stringContainer.getItem().toUpperCase()); // No need to cast


// Integer container
Container<Integer> integerContainer = new Container<Integer>();
integerContainer.setItem(123);

//integerContainer.setItem("123"); // compilation error, type safety checking

System.out.println(integerContainer.getItem().intValue()); // No need to cast

}

}

容器类

class Container<T> {

private T item;

public T getItem(){
return item;
}

public void setItem(T item){

/* If I' doing some thing on item then I have to check the instance of and cast isn't it?

if(item instanceof String){
System.out.println("setItem().((String)item).toUpperCase() : " + ((String) item).toUpperCase());
}
*/

this.item = item;
}
}

引用:http://nandirx.wordpress.com/category/java-2/generics-java/

最佳答案

正如其他人所说,您不应该贬低泛型类型,因为它违背了泛型的目的。

您应该使用绑定(bind)泛型。绑定(bind)泛型允许您要求泛型具有特定类型。这允许您访问特定类型的值,而无需进行强制转换。

这对于 String 类没有意义,因为 String 被标记为 Final,因此无法扩展,但为了将来,请尝试这样的事情。

public interface Shape{
double getArea();
}

public class Rectangle implements Shape{
double width;
double height;
public double getArea(){ return width*height;}
}

//this collection can hold Shape, or any type implementing shape.
public class MyShapeCollection<T extends Shape>{
List<T> shapes;
public double getAreaSum(){
double areaSum = 0;
for(Shape s : shapes){
areaSum += s.getArea();
}
return areaSum;
}
}

public static void main(String[] args){
MyShapeCollection<Rectangle> rectangles = new MyShapeCollection<Rectangle>();

//bad code monkey. String does not implement Shape!
//this line won't compile. including it for demonstration purposes.
MyShapeCollection<String> willNotCompile = new MyShapeCollection<String>();
}

如果您的集合仅包含字符串,则不需要泛型。

关于java - 在java中的通用类内部进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24644507/

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