In Java, what does it mean when a type is followed by angle brackets (as in List)?

后端 未结 7 764
闹比i
闹比i 2020-12-21 02:34

I saw sometimes a type object inside <> beside of another object type declaration. For instance:

NavigableMap colorMap = new Tree         


        
相关标签:
7条回答
  • 2020-12-21 03:00

    As some others said before: Your dealing with Java Generics. They're in Java since SDK 1.5.

    E.g:

    new CopyOnWriteArrayList<EventListener>()
    

    means that you're creating a new (concurrent) ArrayList which is able to store objects of type EventListener. If you would create an ArrayList the old (pre Java 1.5) way like:

    new ArrayList()
    

    All contained objects would be of type Object and you would have to cast them to their real type. See also http://en.wikipedia.org/wiki/Generics_in_Java#Motivation_for_generics.

    0 讨论(0)
  • 2020-12-21 03:05

    They're called Generics, and allow the compiler to do type checking of contents of lists etc, and also reduces the amount of casting you have to do in your code.

    It's also helpful when reading code, as you know what type of object can be put into the item in question, or what type to expect out of it.

    Java's implementation isn't as thorough as C++, as Java's is only available at compile time.

    At runtime, the type information is no longer available.

    0 讨论(0)
  • 2020-12-21 03:08

    These are called Generics in Java. They give you a way to tell the compiler what type the collection is going to hold.

    http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html

    0 讨论(0)
  • 2020-12-21 03:09

    These are called Generics. Here http://java.sun.com/docs/books/tutorial/java/generics/index.html is a tut from sun for them.

    0 讨论(0)
  • 2020-12-21 03:12

    They are Generics, classes that are written with one or more types left to be specified later, so they can be used with any type. The generics can be very useful for containers or algorithms, where the algorithm or the data structure used is independent from the actual type stored or manipulated.

    0 讨论(0)
  • 2020-12-21 03:14

    In your example TreeMap the key of the TreeMap has type Double and the value referenced by this key has the type Integer. And as already answered it's called generics. This is an extension introduced in java 1.5. This makes code more readable

    0 讨论(0)
提交回复
热议问题