0

I am using Java1.7 and using generics.

I wrote a generic class as below.

 public class SomeCollection<T extends MyPojo<K>, K> {



    }

Now, how can i instantiate above class? I mean how can i create an instance for above class?

I am doing as: SomeCollection<MyPojoSubClass, SomeType> sss = new SomeCollection<>(); Compiler is not giving any error. IS it correct way ?

Thanks!

user755806
  • 6,565
  • 27
  • 106
  • 153
  • 3
    `SomeCollection,String>> collection = new SomeCollection<>();` assuming you have not made the default constructor private and you use a string as a "key" (K) - however - keys are usually used as the first generic type and should consist of an immutable class - else you won't be able to retrieve the value which belongs to the key. – Roman Vottner Jan 09 '14 at 10:26
  • Replace T and K with your desired class. And create the object as usual you create in java – Rahul Jan 09 '14 at 10:29
  • I am doing as: SomeCollection sss = new SomeCollection<>(); Compiler is not giving any error. IS it correct way ? – user755806 Jan 09 '14 at 10:39
  • only if MyPojoSubClass is defined like `class MyPojoSubClass extends MyPojo` – mvieghofer Jan 09 '14 at 10:40
  • Yes..correct..Thanks much... – user755806 Jan 09 '14 at 10:42

1 Answers1

3
new SomeCollection<MyPojo<String>, String>(); 

Or are we missing something?

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • @user755806 yup it is correct. that is called the diamond operator and it is specific for java 7, it was made so that we do not type that much. – Eugene Jan 09 '14 at 10:42