3

As far as i know, the generics are only useful at compilation time.

Thus it is possible to declare:

private Set set = new HashSet<String>();

And then, in this string hashset, to add dogs or anything to that set, without any problem since there is not any check at runtime like for arrays (ArrayStoreException...) (but you may have problems like a classcast when you use that set...

So what i want to say is, we usually instantiate generic collections that way:

Set<String> set = new HashSet<String>();

My question is, why do we put the type of the HashSet, since only the type of the reference of the variable is really important (i think).

I mean, we could simply write:

Set<String> set = new HashSet();

And it would work exactly the same right? So why do we usually write the type during the instantiation? (it's not mandatory)


Edit

I know about the "diamond operator" for type inference but why do we even need it!!! since type inference is already working!

The following code :

            Set<String> set = new HashSet();
            set.add("Test add a string 1");
            set.add("Test add a string 2");
            for ( String s : set ) {
                    System.out.println(s);
            }

Produces the output:

Test add a string 1 Test add a string 2

Test it yourself http://ideone.com/vuiCE

So now you talk about type inference as a Java7 feature, but it is already working for me...

With java7 i will have to replace my

            Set<String> set = new HashSet();

By

            Set<String> set = new HashSet<>();

It's still 2 extra characters for doing exactly the same thing no? (Unless generics are not only compile time with Java7? I don't know)

Sebastien Lorber
  • 89,644
  • 67
  • 288
  • 419
  • Some progress on that direction in Java 7: http://download.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html. – rodrigoap Nov 04 '11 at 14:10

5 Answers5

4

And it would work exactly the same right?

In runtime: Yes.

In compile time: No

Your code would be assigning a set containing arbitrary objects, to a variable storing a set containing strings which is bad, and will be frowned upon by the type-checker.

When you write new HashSet() you're using a raw type. I refer to this question regarding it's meaning, and why it should be avoided:


In general, you could argue like this:

Set<String> set = new HashSet();

is not far from

HashSet tmp = new HashSet();
...
Set<String> set = tmp;

which in turn is not far from

HashSet tmp = new HashSet();
tmp.add(7);
...
Set<String> set = tmp;

Which still compiles, but is bad for a thousand reasons :)


Java 7 allows you to write

Set<String> set = new HashSet<>();

though, which tells the compiler to infer the type between the <...>.

Documentation on the "diamond operator":

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • I really don't see why it's bad to assign an object set to a string set variable, since it's exactly what we get at runtime, and it's perfectly legal at compile time (check yourself) – Sebastien Lorber Nov 04 '11 at 14:21
  • It's not *perfectly* legal at compile time ;-) With the default compiler settings, you get a nasty warning (for a good reason!). A `HashSet` can contain for instance an `Integer`. What happens if you assign a set containin an `Integer` to a `Set`? – aioobe Nov 04 '11 at 14:25
  • A warning doesn't mean it's illegal, since legacy code is that way! it IS perfectly legal! – Sebastien Lorber Nov 04 '11 at 14:35
  • Actually, we could do exactly the same "is not far" blabla with the diamond operator no? I mean Set set = new HashSet<>(); is not far from HashSet tmp = new HashSet<>(); tmp.add(7); Set set = tmp; – Sebastien Lorber Nov 04 '11 at 14:40
  • Set set = new HashSet(); is for me very far to what you say since we can't add anything wrong (unless you play a bit) when you assign and instantiate the object that way... there is always a way to insert bad data into generics... – Sebastien Lorber Nov 04 '11 at 14:41
  • In your limited, one-line example, I suppose you could safely suppress the warning. In other scenarios, the very same warning is quite useful, so removing the warning all together is out of the question. I guess the diamond syntax is a two-character shortcut for *safely* suppressing the warning. – aioobe Nov 04 '11 at 15:07
  • @Sebastien ignoring Warnings in general is perfectly legal(even in RL). Its just a matter of what you(can) do when you ignore it and then bad things happen. In a 3 line example its not a problem. >>10KLOC full of warnings is a different thing. – Stefan Nov 04 '11 at 16:25
3

Your suggestion at the end is type inference and has been introduced in Java 7 via the so-called diamond operator:

Set<String> set = new HashSet<>();

So yes, that could've just been there from the beginning. But this is Java and it usually takes several decades to get a new language feature approved (<-- slight exaggeration)

G_H
  • 11,739
  • 3
  • 38
  • 82
1

Although Java currently erases generic type info, they have been extremely careful to design the language and libraries so that it is possible in future to add back full generic type info (so called reification). Any correctly written generic code (i.e. without any javac warning) will survive such language change. In your example, the diamond version is future proof; the raw version is not - it still must compile of course, but it will throw type cast exception at runtime.

Yet, this future-compatibility is a completely delusional. Erasure will stay with us forever. If full reification is introduced, it is safe to say almost all non trivial generic code will break, because everybody is writing incorrect generic code.

It is not our fault. Java forces us to. It gives us the bullshit erasure, and we have no choice but to hack around it to implement stuff. Our code is full of dependencies on detail knowledge of erasure.

JDK is the most guilty one. JDK APIs are carefully designed to survive reification; however the implementations depend on erasure. If Java adds reification, these JDK codes must be rewritten. Java team will be extremely hypocritical if they blame us for writing incorrect code while they must do the same thing themselves.

Given the amount of code that cannot survive reification without rewrite, we can safely say Java is never going to add reification, as long as it keeps the commitment on backward compatibility.

In that case, yeah, whatever. Nothing really terrible about Set<String> set = new HashSet(). Personally I always add <> to avoid the warning. (Actually whenever possible I'll try to make my code reification-proof, which is, as I said, a delusional act)

In your example, inference is trivial. There can be more complex case where <> inference is not so trivial, its type checking can be helpful, which the raw version lacks.

class Foo<T>
{
    Foo(Class<T> clazz){}
}

Foo<String> foo1 = new Foo(Integer.class);    // compiles (wrongly) 

Foo<String> foo2 = new Foo<>(Integer.class);  // does not compile
irreputable
  • 44,725
  • 9
  • 65
  • 93
  • thanks. It would be great to have "reification as an option" for exemple with a system property -Druntime.generics=true or something like that, to let the choice to anybody to do what he wants... – Sebastien Lorber Nov 05 '11 at 11:39
0

Java 7 addresses the addition of limited type inference for class instance creation expressions. In cases where parametrized types need to be explicitly declared for a constructor, and the full parametrized type < T1 , T2 , ...Tn > of that constructor is obvious from the context, then the parameterized type of the constructor can be replaced with an empty set of type parameters: <>. The <> construct is legal to use when constructing an ob ject and either assigning it to a variable, or when passing it as a parameter.

For details : click here

java_mouse
  • 2,069
  • 4
  • 21
  • 30
0

Actually it is not required. If you type

Set<String> s = new HashSet();

the code compiles and we get a warning which we can check with Xlint.

Note: filetest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

Then if we try to add an integer value for example we get a compile error.

Mechkov
  • 4,294
  • 1
  • 17
  • 25
  • Yeah that's exactly what i mean, we can do that and it works so why do another thing or invent a new "diamond operator". For type inference they just should remove that warning... – Sebastien Lorber Nov 04 '11 at 14:19
  • 1
    @SebastienLorber That's actually a pretty good question... Why have a diamond operator in the first place? Backwards compatibility? I hadn't given it any thought, really. – G_H Nov 04 '11 at 14:28