A
collection is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
- HashMap :- Hash table based implementation of the Map interface.
- Permits null values and the null key.
- This class makes no guarantees as to the order of the map.
- HashTable :
- Null vaule and Key not allowed.
- To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the
hashCode
method and the equals
method. - Hashtable is synchronized.
- Comparable and Comparator :- An implementation of the Comparable interface allows the user to create a specific strategy to compare with another object(which should be mutually comparable).The Comparator on the other hand doesn't tie you with a single comparison strategy.
- Comparable interface has “compareTo” method which is normally used for natural ordering but Comparator interface has “compare” method which takes two arguments. It can be used where you want to sort objects based of more then one parameter.
- The java.util.Collections class has an overloaded sort method(i.e. other than sort(List) that accepts a List and a Comparator as an argument.
- Sample Code :-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class Employee implements Comparable { private String name; private int age;
public Employee(String name, int age) { this.name = name; this.age = age; }
public int compareTo(Employee e) { //Write the code for sort. }
} |
1 2 3 4 5 6 7 8 9 10 11 12 13
| public class Main { public static void main(String[] args) { List employeeList = new ArrayList(); employeeList.add( new Employee("Ranga", 10) ); employeeList.add( new Employee("Madhu", 11) ); employeeList.add( new Employee("Babu", 12) );
Collections.sort(employeeList);
} |
Vector and ArrayList
- Arraylist is not synchronized while vector is.
- Arraylist has no default size while vector has a default size of 10.
- Arraylist don't define any increment size while vector does.
- Arraylist can be seen directly without any iterator while vector requires an iterator to display all it's content. (not very sure).
- Sometimes
Vector
is better; sometimes ArrayList
is better. Chose based on your requirement. If u don't need thread-safe collection, then use the ArrayList
.
- A
Vector
defaults to doubling the size of its array, while the ArrayList
increases its array size by 50 percent. Depending on how you use these classes, you could end up taking a large performance hit while adding new elements. Vector
does possess a slight advantage since you can set the increment value. - Traversing an
ArrayList
is since you can simply use an index instead of having to create an iterator.
No comments:
Post a Comment