List 是什么意思? java中的泛型是什么意思?

发布于 2024-08-13 15:10:12 字数 109 浏览 8 评论 0 原文

List 是什么意思,它是否只是表示未指定类型的对象列表?

谷歌搜索字符串 没有返回任何有用的结果(:

What does List<?> mean, does it mean simply a list of objects of unspecified type?

Googling for the string <?> returns nothing useful (:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

绮烟 2024-08-20 15:10:12

正如 Tom 所说,?,或无界通配符,意味着未指定对象的类型。它可能是未知的,可能意味着多个可能的值,或者可能完全不相关。您的示例 List 发音为“List ofknown”。它很方便,因为它很灵活,但也有一些陷阱,因为你不能将随机对象放入未知组中并将它们从未知组中拉出而完全不受惩罚。

资源:

  • Java 教程中的此处讨论了通配符。
  • Angelika Langer 在此处提供了一篇关于泛型的很好(虽然很详细)的教程。 。
  • 这里还有另一篇很好的概述,作者是 Gilad Bracha;查看第 5-7 页。
  • 最后,如果您能获得 Josh Bloch 所著的《Effective Java》,其中有一个关于泛型的精彩部分,以及您可以、不可以、应该和不应该使用通配符的情况(第 1 章) 5,第二版第 109-146 页)。

顺便说一句,您的 Google 搜索失败了,因为 Google 不使用特殊字符:

除了某些例外,标点符号会被忽略(即,您无法搜索 @#$%^&*()=+[]\ 和其他特殊字符)。

-Google 帮助页面

(编辑:我一定是当我昨晚写这篇文章时真的很累。)

As Tom said, the ?, or unbounded wildcard, means that the type of the object is not specified. It could be unknown, could be meant for multiple possible values or might be just plain irrelevant. Your example, List<?>, is pronounced "List of unknown." It's convenient because it's flexible, but there are also some pitfalls because you can't shove random objects in and pull them out of groups of unknown with total impunity.

Resources:

  • Wildcards are discussed here in the Java tutorial.
  • There's a good -- if verbose -- tutorial on generics in general by Angelika Langer available here.
  • And there's another good overview here (PDF) by Gilad Bracha; check out pages 5-7.
  • Finally, if you can get your hands on Effective Java by Josh Bloch, it's got a great section on generics and the cases in which you can, can't, should and shouldn't use wildcards (chapter 5, pages 109-146 in the second edition).

Incidentally, your Google search failed because Google doesn't truck with special characters:

With some exceptions, punctuation is ignored (that is, you can't search for @#$%^&*()=+[]\ and other special characters).

-Google help page

(EDIT: I must have been really tired when I wrote this last night. Cleaned up formatting/added a little info.)

碍人泪离人颜 2024-08-20 15:10:12

您需要获取更多信息的关键字是 通配符

The keyword you need to get more information is Wildcards

滿滿的愛 2024-08-20 15:10:12

为了回答这个问题,我需要解释一下无界通配符和有界通配符。
这篇文章的内容是根据 java 文档汇编而成的。

1.无限通配符

无界通配符类型使用通配符 (?) 指定,例如 List。这称为未知类型列表。在两种情况下,无界通配符是一种有用的方法:

  • 如果您正在编写一个可以使用 Object 类中提供的功能来实现的方法。

  • 当代码使用泛型类中不依赖于类型参数的方法时。例如,List.sizeList.clear。事实上,Class 之所以被如此频繁地使用,是因为 Class 中的大多数方法都不依赖于 T。< /p>

2. 有界通配符

考虑一个简单的绘图应用程序,它可以绘制矩形和圆形等形状。为了在程序中表示这些形状,您可以定义一个类层次结构,如下所示:

public abstract class Shape {
    public abstract void draw(Canvas c);
}

public class Circle extends Shape {
    private int x, y, radius;
    public void draw(Canvas c) {
        ...
    }
}

public class Rectangle extends Shape {
    private int x, y, width, height;
    public void draw(Canvas c) {
        ...
    }
}

这些类可以在画布上绘制:

public class Canvas {
    public void draw(Shape s) {
        s.draw(this);
   }
}

任何绘图通常都会包含许多形状。假设它们被表示为一个列表,那么在 Canvas 中有一个方法来绘制它们将会很方便:

public void drawAll(List<Shape> shapes) {
    for (Shape s: shapes) {
        s.draw(this);
   }
}

现在,类型规则规定 drawAll() 只能在完全形状的列表上调用:例如,它不能在 List 上调用>。不幸的是,因为该方法所做的只是从列表中读取形状,因此也可以在 List 上调用它。我们真正想要的是该方法接受任何形状的列表:
公共无效drawAll(列表形状){
...
}
这里有一个很小但非常重要的区别:我们用 ListList 。扩展形状>。现在,drawAll() 将接受 Shape 的任何子类的列表,因此如果需要,我们现在可以在 List 上调用它。

列表 是有界通配符的示例。 ? 代表未知类型,但是,在本例中,我们知道该未知类型实际上是 Shape 的子类型。 (注意:它可以是 Shape 本身,也可以是某个子类;它不需要从字面上扩展 Shape。)我们说 Shape 是通配符的上限

类似地,语法 ? super T 是有界通配符,表示未知类型,是 T 的超类型。
ArrayedHeap280<?例如,super Integer>包括ArrayedHeap280ArrayedHeap280ArrayedHeap280
正如您在 Integer 类的 Java 文档,Integer 是 Number 的子类,而 Number 又是 Object 的子类。

To answer this question I need to explain Unbounded Wildcards and Bounded Wildcards.
The content of this post has been assembled from java documentation.

1. Unbounded Wildcards

The unbounded wildcard type is specified using the wildcard character (?), for example, List<?>. This is called a list of unknown type. There are two scenarios where an unbounded wildcard is a useful approach:

  • If you are writing a method that can be implemented using functionality provided in the Object class.

  • When the code is using methods in the generic class that don't depend on the type parameter. For example, List.size or List.clear. In fact, Class<?> is so often used because most of the methods in Class<T> do not depend on T.

2. Bounded Wildcards

Consider a simple drawing application that can draw shapes such as rectangles and circles. To represent these shapes within the program, you could define a class hierarchy such as this:

public abstract class Shape {
    public abstract void draw(Canvas c);
}

public class Circle extends Shape {
    private int x, y, radius;
    public void draw(Canvas c) {
        ...
    }
}

public class Rectangle extends Shape {
    private int x, y, width, height;
    public void draw(Canvas c) {
        ...
    }
}

These classes can be drawn on a canvas:

public class Canvas {
    public void draw(Shape s) {
        s.draw(this);
   }
}

Any drawing will typically contain a number of shapes. Assuming that they are represented as a list, it would be convenient to have a method in Canvas that draws them all:

public void drawAll(List<Shape> shapes) {
    for (Shape s: shapes) {
        s.draw(this);
   }
}

Now, the type rules say that drawAll() can only be called on lists of exactly Shape: it cannot, for instance, be called on a List<Circle>. That is unfortunate, since all the method does is read shapes from the list, so it could just as well be called on a List<Circle>. What we really want is for the method to accept a list of any kind of shape:
public void drawAll(List shapes) {
...
}
There is a small but very important difference here: we have replaced the type List<Shape> with List<? extends Shape>. Now drawAll() will accept lists of any subclass of Shape, so we can now call it on a List<Circle> if we want.

List<? extends Shape> is an example of a bounded wildcard. The ? stands for an unknown type, however, in this case, we know that this unknown type is in fact a subtype of Shape. (Note: It could be Shape itself, or some subclass; it need not literally extend Shape.) We say that Shape is the upper bound of the wildcard.

Similarly, the syntax ? super T, which is a bounded wildcard, denotes an unknown type that is a supertype of T.
A ArrayedHeap280<? super Integer>, for example, includes ArrayedHeap280<Integer>, ArrayedHeap280<Number>, and ArrayedHeap280<Object>.
As you can see in the java documentation for Integer class, Integer is a subclass of Number that in turn is a subclass of Object.

淡看悲欢离合 2024-08-20 15:10:12
  • List:完全没有类型限制和赋值限制。
  • List:看起来和List使用一样,但是接受其他泛型赋值时会出现编译错误。
  • List:它是一个泛型类型。赋值前,意味着它可以接受任何类型的集合赋值,但赋值后,你不能向其中添加元素,但可以删除明确,而不是不可变集List 一般用作参数来接收外部集合,或者返回特定元素类型的集合,也称为通配符集合

测试代码及结果如下:

        List a1 = new ArrayList();
        a1.add(new Object());
        a1.add(new Integer(10));
        a1.add(new String("string"));

        System.out.println("List is : " + a1);

        List<?> a4 = a1;
        a4.remove(0);
        System.out.println("List is : " + a4);

        System.out.println("List is : " + a4.get(0));
        
        a4.clear();
        System.out.println("List is : " + a4);

结果为:

List is : [java.lang.Object@2a139a55, 10, string]
List is : [10, string]
List is : 10
List is : []
  • List: There is no type restriction and assignment restriction at all.
  • List<Object>: It seems to be used the same as List, but a compilation error will occur when accepting other generic assignments.
  • List<?>: It is a generic type. Before assignment, it means that it can accept any type of set assignment, but after assignment, you can't add elements to it, but you can remove and clear, not an immutable set. List<?> is generally used as a parameter to receive an external collection, or return a collection of specific element types, also known as a wildcard collection.

The test code and result as followed:

        List a1 = new ArrayList();
        a1.add(new Object());
        a1.add(new Integer(10));
        a1.add(new String("string"));

        System.out.println("List is : " + a1);

        List<?> a4 = a1;
        a4.remove(0);
        System.out.println("List is : " + a4);

        System.out.println("List is : " + a4.get(0));
        
        a4.clear();
        System.out.println("List is : " + a4);

The result is :

List is : [java.lang.Object@2a139a55, 10, string]
List is : [10, string]
List is : 10
List is : []
当梦初醒 2024-08-20 15:10:12

听起来您应该寻找一些有关 Java 泛型的文档。

List表示它是基于当前未指定类型的对象。该规范是在类实例化时制定的。

例如:

List<String> listOfStrings = new ArrayList<String>();

是一个 String 对象的列表。

Sounds like you should look for some documentation on Java generics.

The List<?> means that it is an object based on a currently unspecified type. That specification is made when the class is instantiated.

For example:

List<String> listOfStrings = new ArrayList<String>();

is a list of String objects.

戈亓 2024-08-20 15:10:12

List 代表 List 所以在 Collection 中你会发现 containsAll(Collection c) 它允许你写

List<Object> objs = Arrays.<Object>asList("one",2,3.14,4);
List<Integer> ints = Arrays.asList(2,4);
assert objs.containsAll(ints);//true

List<?> stands for List<? extends Object> so in Collection<E> you will find containsAll(Collection<?> c) which allows you to write

List<Object> objs = Arrays.<Object>asList("one",2,3.14,4);
List<Integer> ints = Arrays.asList(2,4);
assert objs.containsAll(ints);//true
梦年海沫深 2024-08-20 15:10:12

List 是一个您可以自己实现的接口,也可以由一些 Java 集合实现,例如 Vector

您可以使用尖括号提供编译时类型信息。最通用的类​​型是Object,即List。您看到的 表示 Object 的某些子类或 Object 的列表。这就像说 List,还是 List<? extends Foo>,其中 List 包含 Foo 某些子类的对象或 Foo 本身的对象。

您无法实例化 List;它是一个接口,而不是一个实现。

List is an interface you can implement yourself and also implemented by some of the Java collections, like Vector.

You can provide compile-time typing information using the angled brackets. The most generic type would be Object, which would be List<Object>. The <?> you see is indicating a List of some subclass of Object or an Object. This is like saying List<? extends Object>, or List<? extends Foo>, where the List contains objects of some subclass of Foo or objects of Foo itself.

You can't instantiate a List; it's an interface, not an implementation.

鸠魁 2024-08-20 15:10:12

当您从 Collection 中取出一个元素时,必须将其转换为存储在集合中的元素类型。这除了不方便之外,也不安全。编译器不会检查您的转换是否与集合的类型相同,因此转换可能在运行时失败。

泛型为您提供了一种将集合类型传达给编译器的方法,以便可以对其进行检查。一旦编译器知道集合的元素类型,编译器就可以检查您是否一致地使用了该集合,并且可以对从集合中取出的值插入正确的转换。

chk pdf

When you take an element out of a Collection, you must cast it to the type of element that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does not check that your cast is the same as the collection's type, so the cast can fail at run time.

Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that you have used the collection consistently and can insert the correct casts on values being taken out of the collection.

chk dis pdf

如歌彻婉言 2024-08-20 15:10:12

?只不过是泛型中的通配符

泛型中有 3 种不同类型的通配符

1) 上界通配符:使用扩展关键字

eg: List<? extends SuperClass>

2) 下界通配符

eg:Uses Super key word List<? super SubClass>

3) 无界通配符

List<?> list

? is nothing but Wildcard in Generics

There are 3 different kind of Wildcards in Generics

1) Upper Bounded Wildcards: Uses extends key word

eg: List<? extends SuperClass>

2) Lower Bounded Wildcards

eg:Uses Super key word List<? super SubClass>

3) Unbounded Wildcard

List<?> list
2024-08-20 15:10:12

列表相当于列表

通配符? extends Object 相当于无界通配符 ?

Java 规范中的泛型

List<?> is equivalent to List<? extends Object>

The wildcard ? extends Object is equivalent to the unbounded wildcard ?

<?> in java specification

Generics in java specification

宁愿没拥抱 2024-08-20 15:10:12

您可能正在查看基于模板的 List 类。您可以通过 List 创建字符串列表myList = new MyList(); 作为示例。检查文档以了解它支持的所有类型。它应该支持任何对象类型,但如果有排序功能,则必须提供一些比较函数。

请注意,在上面的示例中,MyList 是一个在 Java 中实现 List 接口的具体类。它可以是ArrayList。

编辑:
我错误地将 List 假设为具体类。修正了上面的错误。谢谢乔恩。

You are probably looking at the template based List class. You can create a list of strings by List<String> myList = new MyList<String>(); as an example. Check the documentation for all the types it supports. It should support any object type, but if there is a sort functionality you have to supply some compare functions.

Note that in the example above MyList is a concrete class that implements the List interface in Java. It can be ArrayList.

EDIT:
I assumed List as a concrete class by mistake. Fixed the error above. Thanks Jon.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文