What is Templating with <?> Do in Java SE6?

Possible duplicate:
Question marks in Java generics.

I am editing another user's code for an assignment, and I am trying to clear it to get rid of dozens of warnings in it, and Eclipse gave warnings about using Collections as a raw type. When I suggested that fix it, it created it.

Collections<?> 

Example

 public static String separatedString(Collection<?> c, String separator) { return separatedString(c, "", separator, "", new StringBuffer()) .toString(); } 

I'm just wondering what it was done and whether it was safe.

+4
source share
2 answers

This is the concept of generics .

All About Object Oriented Programming

For example, if I declare a variable as Collection<MyClass> ONLY and ONLY objects that have a declared type or subtype of MyClass can be placed in it.

It's good to keep things straight and set limits on how you use this code.

A question mark indicates the class of your choice.

When you initialize a class, you can ... scream, just seeing that there is an exact duplicate here: What does the question mark in a parameter of type generics Java mean?

+1
source

Adding

 MyClass<?> 

adds generics to the code, but doesn’t actually add many benefits, since a bare question mark can mean any class. Google and read about generics, and you will learn how to create generics that restrict which classes can be used and how this adds the benefits of compilation type checking.

eg,

 MyClass<? extends Comparable> 

Which will restrict encoders to only using comparable types with MyClass. The basic tutorial starts here: Java Generics Tutorial

0
source

Source: https://habr.com/ru/post/1342415/


All Articles