4

Possible Duplicate:
Question marks in Java generics.

I'm editing someone else's code for an assignment and I'm trying to clean it up to get rid of the dozens of warnings in it and Eclipse was giving warnings for the use of Collections as a raw type. When I took it's suggested fix it created this.

Collections<?>

Example

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

I was just wondering exactly what this did and whether or not it was safe.

Community
  • 1
  • 1
baantacron
  • 41
  • 1
  • 2

2 Answers2

1

This ist the concept of generics.

Its all about object oriented programming

For example if i declare a variable as Collection<MyClass> ONLY and ONLY objects that are of declared Type or Subtype of MyClass may be put in it.

This is good to keep things straight and put constraints on the way this code should be used.

The question mark stands for class of your choice.

When you initialise the class you can ... whoops just seeing there is an exact duplicate here: What does the question mark in Java generics' type parameter mean?

Community
  • 1
  • 1
The Surrican
  • 29,118
  • 24
  • 122
  • 168
0

Adding

MyClass<?>

adds generics to the code, but doesn't really add much benefit since the naked question mark can mean any class. Google and read up on generics, and you'll learn how to create generics that do constrain what classes may be used and how this adds the benefit of compile-time type checking.

e.g.,

MyClass<? extends Comparable>

Which will constrain coders to only using Comparable types with MyClass. A basic tutorial starts here: Java Generics Tutorial

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373