9252

Using Generics on right hand side in Java 6?

I java 6 i can declare the arraylist as follows

Way1: using generics i.e <Integer> on right hand side too

List<Integer> p = new ArrayList<Integer>();

Way2: using the diamond operator

List<Integer> p = new ArrayList<>();

Way3: using generic only at left side

List<Integer> p = new ArrayList();

I prefer to use way 3 as its brief. Is there any difference between these ways? Which one we should prefer and why?

<strong>Update:-</strong> I know in java 7 second way is recommended but my question is in context of java 6. Which one is preferable?

To me, way 3 also says p is an arraylist of integers (same conveyed by way1). So I find no difference except the fact IDE displays warning message:

ArrayList is a raw type. References to generic type ArrayList<E> should be parameterized

Answer1:

As has been pointed out, Way 2 isn't valid in 1.6. So the question is, is there any difference between Way 1 and Way 3. Apart from readability, no.

Take this code:

import java.util.*; class G { public static void main(String [] args){ List<Integer> listOne = new ArrayList<Integer>(); listOne.add(1); int one = listOne.get(0); List<Integer> listTwo = new ArrayList(); listTwo.add(1); int two = listTwo.get(0); } }

Compile it and look at the bytecode using javap -c

public static void main(java.lang.String[]); Code: // FOR listOne 0: new #2 // class java/util/ArrayList 3: dup 4: invokespecial #3 // Method java/util/ArrayList."<init>":()V 7: astore_1 8: aload_1 9: iconst_1 10: invokestatic #4 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 13: invokeinterface #5, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 18: pop 19: aload_1 20: iconst_0 21: invokeinterface #6, 2 // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object; 26: checkcast #7 // class java/lang/Integer 29: invokevirtual #8 // Method java/lang/Integer.intValue:()I 32: istore_2 // FOR listTwo 33: new #2 // class java/util/ArrayList 36: dup 37: invokespecial #3 // Method java/util/ArrayList."<init>":()V 40: astore_3 41: aload_3 42: iconst_1 43: invokestatic #4 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 46: invokeinterface #5, 2 // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z 51: pop 52: aload_3 53: iconst_0 54: invokeinterface #6, 2 // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object; 59: checkcast #7 // class java/lang/Integer 62: invokevirtual #8 // Method java/lang/Integer.intValue:()I 65: istore 4 67: return }

We can see that the exact same bytecode is produced in both cases. Note that as Generics aren't baked in the compiler throws away the information after checking it at compile time and adds in checkcast instructions to make sure the casts it does when retrieving objects are safe.

Answer2:

The second way is not possible in Java 6. It is the new way of inferring Generic instance in Java 7.

Answer3:

There is no difference, if you are using java 7 prefer the second method, but is it not available in java 6. It is a new addition to java 7.

Answer4:

Both are same but way2 is available from java 7

Answer5:

Both are same .But there are version difference in both of this.

But second way is not possible in java 6.In Java 7 if we not declare type in right side then by default it will take same type as left side.

http://docs.oracle.com/javase/7/docs/technotes/guides/language/type-inference-generic-instance-creation.html

So as per your updates, if you have to use Java 6,then you should use way1.

Answer6:

Way 3 uses raw types. You should never use raw types. They should only be used in legacy code.

Answer7:

Way 3 is not good. Mixing Generics and raw types is naughty, as you are making an assumption for runtime about types, and can run into ClassCastExceptions like the following code:

ArrayList b = new ArrayList(); b.add(5); ArrayList<String> a = new ArrayList(b); System.out.println(a.get(0));

So for Java 6, always use way 1

Recommend

  • Matlab: Fundamental limitations of struct array?
  • PDF in PHP ZipArchive throwing errors, server permissions
  • PDF page count using regex
  • Password strong - not require each condition
  • Ansible syntax best practice, YAML dictionary (key: value) or equal sign (key=value)?
  • Regarding client side code generation from WSDL
  • Delete std::shared_ptr without destroying the managed object?
  • Laravel lmutator $this->attributes return 'Undefined index: id'
  • How to set an entity field that does not exist on the table but does exists in the raw SQL as an ali
  • Count from each distinct date, fill in missing dates with zero
  • my tic-tac-toe program in matlab does not work [closed]
  • Changing Jupyter Notebook start up folder by modifying “start in” not working any more
  • drawing random circles, storing their coorindates in an array
  • Android Database Error - getWriteableDatabase
  • How to use function wrapper in mustache.php?
  • What is the purpose of TaskExecutor in spring?
  • how to find common suffix in java by using method
  • MySQL Order by column = x, column asc?
  • Could not find rake using whenever rails
  • Can Jackson SerializationFeature be overridden per field or class?
  • sending/ receiving email in Java
  • Why winpcap requires both .lib and .dll to run?
  • Return words with double consecutive letters
  • Cannot Parse HTML Data Using Android / JSOUP
  • How to delete a row from a dynamic generate table using jquery?
  • Python: how to group similar lists together in a list of lists?
  • Proper way to use connect-multiparty with express.js?
  • Acquiring multiple attributes from .xml file in c#
  • JTable with a ScrollPane misbehaving
  • How to CLICK on IE download dialog box i.e.(Open, Save, Save As…)
  • Java static initializers and reflection
  • How can I remove ASP.NET Designer.cs files?
  • unknown Exception android
  • Checking variable from a different class in C#
  • Busy indicator not showing up in wpf window [duplicate]
  • Observable and ngFor in Angular 2
  • failed to connect to specific WiFi in android programmatically
  • Unable to use reactive element in my shiny app
  • java string with new operator and a literal
  • How can I use threading to 'tick' a timer to be accessed by other threads?