Java Collection Best Practices
There are the few best practices for Java Collections
1. Decide approximate initial capacity of a collection - As Collection implementations like ArrayList, HashMap, use Array internally for storing, you can speed up things by setting initial capacity.
2. Use ArrayLIst, HahMap etc instead of VEctor , Hashtable to avoid synchronization overhead. Even better use array where ever possible.
3. Program to interface instead of implementation – It gives freedom of switching implementation without touching code.
For Example : Use
List list = new ArrayList();
Avoid :
ArrayList list = new ArrayList();
4. Always return empty collection object instead of null .
For Example : Use
public List getCustomer(){
//...
return new ArrayList(0);
}
Avoid :
public List getCustomer(){
//...
return null;
}
5. Generally you use a java.lang.Integer or
a java.lang.String class as the key, which are immutable Java objects.
6. Avoid exposing collection field – Always provide fine grained methods for collection fields instead of directly exposing setter/getter for collection field.
For Example Use :
class Order
{
List ArrayLisy itemList;
//...public boolean addItem(Item item){
//....
}public boolean removeItem(Item item){
//....
}
}
Avoid :
class Order
{
List ArrayLisy itemList;
//...public void setItems(List items){
//....
}}
7. Avoid storing unrelated or different types of objects into same collection
For Example Use :
public class Order
{
List ArrayLisy itemList;
//...public boolean addItem(Item item){
//....
}public boolean removeItem(Item item){
//....
}public static void main(String [] args){
int id;
String desc;
Order order = new Order();
//...Item item = new Item()[
item.setItem(new Integer(id));
item.setDesc(dec);
order.addItem(item);
//...
}}
public class Item
{
int id;
String desc;public void setId(int id){
//..
}public int getId(){
//..
}public void setDesc(){
//..
}public String getDesc(){
//..
}
}
Avoid :
public class Order
{
List ArrayLisy itemList;
//...public boolean addItem(Item item){
//....
}public boolean removeItem(Item item){
//....
}public static void main(String [] args){
int id;
String desc;
Order order = new Order();
//...List item = new ArrayList()[
item.add(new Integer(id));
item.add(dec);
order.addItem(item);
//...
}}
8. Use Collection framework features instead of traditional approach.
For Example: Use
//search for duplicate names
for (int i=0;i<nameArray.length ;i++ )
{
String name = nameArray[i];
if(nameSet.contains(name)){
System.out.println("Got Duplicate name = " + name );
}
}
Avoid:
//search for duplicate names
for (int i=0;i<nameArray.length ;i++ )
{
String name = nameArray[i];
for(int j=0;j<nameArrayLength;j++){
if(nameArray[j].equals(name)){
System.out.println("Got Duplicate name = " + name );
}
}
}
Comments
Post a Comment