Sunday, 6 February 2011

Using java.util.Collections - 1

One of the most useful classes is the java.util.Collections consisting of static methods that operate on or return collections. So if you need to reverse or sort a list, for example, then don't write the code yourself just look here!
For example, to reverse a list use:

    List<Character> myList = new LinkedList<Character>();
    myList.add
('A');
    myList.add
('B');
    myList.add
('C');
    myList.add
('D');

    System.out.println
("Before:" + myList);
    Collections.reverse
(myList);
    System.out.println
("After: " + myList);

If your list contained Character objects for 'A', 'B', 'C', 'D' then after calling reverse it'll magically contain 'D', 'C', 'B', 'A'.

No comments: