Recently I find some questions about java. 1 【A】
ArrayList dates = new ArrayList();
dates.add(new Date());
dates.add(new String());
【B】
ArrayList<Date> dates = new ArrayList<Date>();
dates.add(new Date());
dates.add(new String());
Do these two pieces have compilation errors? I guess there should be something wrong with add(new String()) but can't make sense clearly.
I cannot find the mistake in this arraylist, is the return type of
dates.get()wrong?ArrayList dates = new ArrayList(); dates.add(new Date()); Date date = dates.get(0);
what if I use this (below)?
ArrayList<Date> dates = new ArrayList<Date>();
dates.add(new Date());
Date date = dates.get(0);
If Student is the subtype of the Person, then which are legal?
Person p = new Student(); Student s = new Person(); List<Person> lp = new ArrayList<Student>(); List<Student> ls = new ArrayList<Person>();
I was struggled with these questions for two days so I really need somebody to give me some explanation. thanks in advance
By default you can put any Object into a List, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a List. Here is an example:
This List can now only have MyObject instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
The below content is from oracle's website
In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs. The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types.
Code that uses generics has many benefits over non-generic code:
Stronger type checks at compile time. A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Elimination of casts. The following code snippet without generics requires casting:
When re-written to use generics, the code does not require casting:
// no cast Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.