3

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 ?

0

4 Answers 4

21

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

Set<T> set = new HashSet<T>();
Sign up to request clarification or add additional context in comments.

5 Comments

I think I understand, but just to make sure : If for example I choose to use List (Linked List) than I would not have to choose the implementation ?
@Belgi, List is also an interface. You still need to choose an implementation, for example List<T> list = new ArrayList<T>();.
@Belgi List is also a interface but LinkedList isn't check right above the summary (public ...)
ok. than should I change my code to HashSet<T> set = new HashSet<T>() ? What is the difference between the two ? (also, thanks for the help!)
@Belgi, the difference is that if you use Set<T> set the set variable sees only the methods that are declared on the interface, whereas if you declare it as a concrete class HashSet<T> set it can use all methods on this concrete class. In general it is considered best practice to work with the highest possible in the hierarchy type which in this case is Set<T>. This allows you to more easily switch between different implementations without this having an impact on the client code.
6

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

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

Comments

2

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>();

Comments

-2

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.

3 Comments

I'm not sure I understand you, assume I have a class T
There is no class T. There is an interface Set and a class HashSet. T is a constraint.
I just swapped myClass for T when I posted this,sorry for the confusion. I have myClass wherevere I wrote T in the post...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.