What is the difference in declaring a collection as such
public class CatHerder{
private List cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
//or
public class CatHerder{
private ArrayList cats;
public CatHerder(){
this.cats = new ArrayList();
}
}
//or
public class CatHerder{
private ArrayList<Cat> cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
ArrayList class is used to create a dynamic array that contains objects. List interface creates a collection of elements that are stored in a sequence and they are identified and accessed using the index. ArrayList creates an array of objects where the array can grow dynamically.
ArrayList of user defined objects Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer , String , Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.
ArrayList provides constant time for search operation, so it is better to use ArrayList if searching is more frequent operation than add and remove operation. The LinkedList provides constant time for add and remove operations. So it is better to use LinkedList for manipulation.
ArrayList cannot hold primitive data types such as int, double, char, and long. With the introduction to wrapped class in java that was created to hold primitive data values. Objects of these types hold one value of their corresponding primitive type(int, double, short, byte).
You should declare it as a List<Cat>
, and initialize it as an ArrayList<Cat>
.
List
is an interface, and ArrayList
is an implementing class. It's almost always preferable to code against the interface and not the implementation. This way, if you need to change the implementation later, it won't break consumers who code against the interface.
Depending on how you actually use the list, you might even be able to use the less-specific java.util.Collection
(an interface which List
extends).
As for List<Cat>
(you can read that as "list of cat") vs List
: that's Java's generics, which ensure compile-time type safely. In short, it lets the compiler make sure that the List
only contains Cat
objects.
public class CatHerder{
private final List<Cat> cats;
public CatHerder(){
this.cats = new ArrayList<Cat>();
}
}
I would do the following.
public class CatHerder{
private final List<Cat> cats = new ArrayList<Cat>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With