This would be very handy as typecasting gets boring fast.
views:
572answers:
3
+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
2008-12-17 12:02:01
Thanks - I'm Flash guy learning Java and neither NetBeans nor google were giving me any help with that one!
Iain
2008-12-17 12:07:55
Some things can be hard to google, i know.
krosenvold
2008-12-17 12:19:36
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é
2008-12-19 13:25:41
+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
2008-12-17 12:03:59
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
2008-12-17 12:06:26
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
2008-12-17 12:18:16
+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
2008-12-19 13:18:22