Casting and generics, any performance difference?

I have been coding in Android a lot lately, although I am comfortable in JAVA, but I lack some ideas about the basic concepts that are used there.

I am interested to know if there is a difference between the two codes.

First method:

//Specified as member variable.   
ArrayList <String> myList  = new ArrayList <String>(); 

and using String temp = myList.get(1);

Second method:

ArrayList myList  = new ArrayList(); //Specified as member variable.   

and using

String temp1 = myList.get(1).toString();   

I know him about casting. The first method has a big advantage over the second, Most of the time in real coding I have to use the second method, because the arraylist can take different types of data, I end up pointing

ArrayList <Object> = new ArrayList <Object>(); 

or more general way.

+5
source share
5 answers

, , , . , , , , , , (, , generics.) , . , , , !

, , .

, (.. - , ) arraylist, ! , , .

+7

, , . :

  • , , .
  • :
  • : , JVM , , ClassCastException. Generics , , .
+6

: .

:

/ ( , ), . , toString(), , generics.

, toString(). (, String s). toString() , , .

+2

android , , . , String ArrayList. , , .

0

- " type erasure".

But if you use Java 1.5 or higher, you should use generics, not weakly typed copies.

Benefits of Generics -

* The flexibility of dynamic binding, with the advantage of static type-checking. Compiler-detected errors are less expensive to repair than those detected at runtime.
* There is less ambiguity between containers, so code reviews are simpler.
* Using fewer casts makes code cleaner. 
0
source

All Articles