Belgi
Belgi

Reputation: 15052

Using generics in Java

I started using Java a while ago so this is probably a silly question for most of you, I want to use Set in my code (assume I have a class T),

Set<T> mySet;

Eclipse gives my an error : The local variable mySet may not have been initialized. Than I tried to initialize it:

Set<T> mySet = new Set<T>();

but than Eclipse gives the error : "Cannot instantiate the type Set".

What am I doing wrong here ?

Upvotes: 3

Views: 4119

Answers (4)

Keen Sage
Keen Sage

Reputation: 1949

Set is an Interface available in java.util. You cannot instantiate an interface. You should use an implementation of set like HashSet, TreeSet etc.

so the declaration should be something like this.

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

or

Set<T> set = new TreeSet<T>();

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533472

In Java, an object is not created on the stack. Instead you have a just a reference which has to be initialised. To create a new object you have to explicitly specify which concrete class is to be used.

Upvotes: -2

rsp
rsp

Reputation: 23373

Set is an interface and cannot be instantiated, you have to chose an implementation of Set, like:

Set<T> mySet = new TreeSet<T>();

Upvotes: 6

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

Set<T> is an interface and cannot be instantiated. You could use HashSet<T>:

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

Upvotes: 21

Related Questions