Re: [array / List]Unknown number of objects
"Daniel Moyne" <dmoyne@tiscali.fr> wrote in message
news:elv50j$rqs$1@news.tiscali.fr...
As a matter of fact I am using this :
ArrayList<String> classnamelist = new ArrayList<String>();
so 2 questions :
(1) what is the difference with List<String>list=newArrayList<String>();
very strange as the name of the object you want to instanciate has a
different name from the name upfront (very uncommon in declaration in
Java).
Inheritance typically (there are exceptions) represents an IS-A
relationship. ArrayList implements List, so you can say that an ArrayList
IS-A List, and a List IS-A Collection, and a Collection IS-A Object, etc.
So when you write (dropping the generics for a moment):
List foo = new ArrayList()
You're basically saying "I wish to declare a reference called 'foo'
whose type is List. I wish to create a new instance of ArrayList, and store
a reference to this newly created ArrayList in 'foo'."
This isn't as uncommon as you think, and I see it fairly often in Java
code. I'm a bit too tired right now to get into the reasons for using this,
but I'll just provide an example that might get you thinking about the
possiblities:
public void bar(boolean doINeedQuickRandomAccess) {
List foo = doINeedQuickRandomAccess ? new ArrayList() : new LinkedList();
/*more code*/
}
(2) adding <String> declares I would assume a string content and this what
I
want but can a list contains any type of objects ?
Right. If you look at the source code for List, it looks something like:
public interface List<E extends Object> extends Collection<E>
E is a "type variable", and there's no real reason they chose "E". They
could have also chosen "J", or "Bob", or any other name. But what the
declaration is saying that that the "type parameter" (String in your case)
has to extend Object, and that a List<E> (where, again, E can be anything
that extends Object) IS-A Collection<E>. So putting in actual values into
the type variable, we have a List<String> IS-A Collection<String>. You might
read this as "A list of strings is a collection of strings".
Type variables don't necessary specify the concept of containment. The
Comparator interface also accepts a generic type argument, which specifies
what kind of objects it will compare. So a comparator which compares two
strings (perhaps in alphabetic order) would have a declaration like:
Comparator<String> myAlphabeticalComparator = new SomeClassIWrote();
- Oliver