Java中的泛型 [英] Generics in Java
问题描述
List< Rectangle> test1 = new LinkedList< Rectangle>();
列表<形状> test2 = test1; //编译器错误;
这当然是假设类Rectangle是Shape的子类。
有人可以向我解释为什么这是一个错误吗?
如果此代码有效,您可以继续插入进入 test2
a Circle
- 因此彻底打破了保证 test1
使得只有 Rectangle
s会被插入。
一般原则(与语言无关 - - 一个逻辑问题 - 即使违反直觉):一袋香蕉不是一袋水果......在一个可变对象的世界里(函数式编程世界中,每个对象一旦创建就不可变,就是很多更简单!)。那是因为你可以给一袋水果加一个苹果(因为苹果是一片水果),但是你不能把一个苹果加到一袋香蕉上(因为苹果不是香蕉)。
顺便说一下,这与矩形不是矩形的原因非常相似(再次,在可变对象的世界中):因为给定一个(可变的)矩形,可以改变双方独立,但是,给一个正方形,你不能。 (在几何中,一个正方形确实是一个矩形 - 但这是因为,在函数式编程的几何中,没有变异一个对象的概念! - )。
I came across something peculiar today. Take a look at this code snippet:
List <Rectangle> test1 = new LinkedList<Rectangle>();
List <Shape> test2 = test1; //Compiler Error;
This is of course is assuming that class Rectangle is a subclass of Shape. Can someone explain to me why this is an error?
If this code worked, you could continue by inserting into test2
a Circle
-- thus utterly breaking the guarantee that test1
makes, that only Rectangle
s will ever be inserted in it.
The general principle (language independent -- a matter of logic -- even though counter-intuitive): a bag of bananas is NOT a bag of fruit... in a world of mutable objects (the functional programming world, where every object is immutable once created, is MUCH simpler!). That's because you can add an apple to a bag of fruit (since an apple is a piece of fruit), but you can't add an apple to a bag of bananas (since an apple is not a banana).
BTW, this is very similar to the reason a square is not a rectangle (again, in a world of mutable objects): because given a (mutable) rectangle you can mutate the two sides independently, but, given a square, you can't. (In geometry, a square IS indeed a rectangle - but that's because, in geometry like in functional programming, there is no concept of "mutating" an object!-).
这篇关于Java中的泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!