tags:

views:

572

answers:

3

This would be very handy as typecasting gets boring fast.

+13  A: 

If you use generics (java 5), you can avoid all casting with

 List<String> myList = new ArrayList<String>();
 myList.add(" a test");
 String temp = myList.get(0);

Unless I am missing something in your question that should cover both needs.

krosenvold
Thanks - I'm Flash guy learning Java and neither NetBeans nor google were giving me any help with that one!
Iain
Some things can be hard to google, i know.
krosenvold
Behind the scenes it still does it the old way by casting the objects b/c generics are only visible at compile time not at runtime.
André
+1  A: 

I don't understand, what's so hard about:

List<Foo> fooList = new ArrayList<Foo>();

I guess you could define a class:

public class FooList extends ArrayList<Foo> {
    ...
}

if you want to avoid the angle brackets...

JeeBee
Extending a concrete class like ArrayList is serious ick. I would prefer to implement List, and forward all operations to an ArrayList that's contained as a member of FooList. Or, you can extend AbstractList.
Chris Jester-Young
ArrayList is the one, thanks.
Iain
Yeah, it isn't nice, for a simple structure like ArrayList with only one class generic, if can be handy when you get something complex like a Graph data structure with Nodes and Edges, all typed with each other! Yes, wrapping it would be nicer, but that's a nitpick against the question.
JeeBee
+1  A: 

If by "variable length" you mean that the size will change over time, then you probably want a LinkedList rather than an ArrayList:

print("List<Foo> fooList = new LinkedList<Foo>();");

That way you get better performance when adding a bunch of elements.

GaryF