Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialDominik Huber
4,631 PointsList<String> results = new ArrayList<String>(); --> Why do I need the braces "()" ?
Hi,
thats one thing that confuses me. Why do I need this braces? Is it because new ArrayList<String> is a method? But why is it writen uppercase then. I thought methods are lowercased?
And when I create an array: String[] test = new String[3]; --> Why do i don't need the braces here?
Thx for clarification :)
And a side question:
If lists are so much better then arrays ( I really figured out why) why do we use / have arrays at all?
2 Answers
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 PointsHi. Answering initial question.
ArrayList
is a simple class in Java. here's the doc : https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
When you instantiate new instance of any class you do this:
SomeClass someClass = new SomeClass();
In this way you instantiate, i.e. create new instance of the class SomeClass
using default constructor.
That is exactly what we do with ArrayList<>()
, we instantiate ArrayList
class with default constructor.
Does it makes sense?
Coming back to arrays: Arrays are primitives, they are not classes, so you cannot write like this:
There are different ways to instatiate array. Take a look here, e.g.
http://alvinalexander.com/blog/post/java/java-faq-create-array-int-example-syntax
The most important when you instantiate array - is to set its size: You have to know size when you instantiate array. That's why the easiest way to create array is to write:
String[] test = new String[3];
This way you are creating array with length of 3, and type String.
markmneimneh
14,132 PointsHi
I think this may help
http://javahungry.blogspot.com/2015/03/difference-between-array-and-arraylist-in-java-example.html
There is no such thing as one is better than the other, you generally use the one best for the job on hond. I myself use both, but since in Java I deal with objects a lot, I tend to use ArrayList more often.
Hope this helps.
Dominik Huber
4,631 PointsHi thx for the link! That helps a lot.
Do you maybe have an answer to my initiale question with the braces () ?
Dominik Huber
4,631 PointsDominik Huber
4,631 PointsThx I get it now :)