View RSS Feed

Eranga

Java ArrayList : Generics & Sorting

Rating: 2 votes, 5.00 average.
by , 07-21-2011 at 06:20 AM (3334 Views)


Abstract

Java ArrayList (ArrayList (Java 2 Platform SE 5.0)) class is a fastest and easiest way to represent one-dimensional array. ArrayList not synchronized, that is cross thread access may cause problems. It holds an ordered item sequence of items (objects) like an array, but there are differences:

  • Size of an ArrayList could change dynamically, by adding or removing elements
  • An ArrayList can hold only object references, not primitives


Compatibility

JDK 1.5 or higher (article related with generics)

Key Features

ArrayList class provides following methods for basic operations. Please read the ArrayList API for the complete list.

boolean add(E o)
- append specified element to the end

E remove(int index)
- remove the element at the specified position of the list. returns the element that was removed from the list

E get(int index)
- returns the element at the specified position of the list

int size()
- returns the number of elements in the list

Example Code

Following example showing a typical use of ArrayList - read a text file and manipulate contents, without knowing how many lines on it.

Java Code:
import java.io.*;
import java.util.*;

/**
 *
 * @author Eranga Thennakoon
 */
public class ArrayListDemo {

    public static void main(String[] args) throws Exception {

        // Use of "Generics", much similar to "Templates" in C/C++
        ArrayList<String> arrList = new ArrayList<String>();

        // Read text from character-input stream
        BufferedReader bufReader = new BufferedReader(new FileReader("java_tips.txt"));

        while(bufReader.ready()){
            String strLine = bufReader.readLine();
            arrList.add(strLine);
        }

        System.out.println("----- Unsorted List -----");

        // Iteration
        Iterator stepper = arrList.iterator();
        while(stepper.hasNext()){
            System.out.println((String)stepper.next());
        }

        System.out.println("\n----- Alphabetic Sort List -----");

        Collections.sort(arrList);

        stepper = arrList.iterator();
        while(stepper.hasNext()){
            System.out.println((String)stepper.next());
        }

        System.out.println("\n----- Sort By Line Length -----");

        // I don't care about the unchecked warnings now
        Collections.sort(arrList, new ArrayListSortByLength());

        stepper = arrList.iterator();
        while(stepper.hasNext()){
            System.out.println((String)stepper.next());
        }
    }

}
and here is the object comparator class that I've use for the non-standard sorting method implementation with the length of String objects. Compare two items and return positive/negative to indicate first comes in first in the sequence and the second in other way, respectively.

Java Code:
/**
 *
 * @author Eranga Thennakoon
 */
public class ArrayListSortByLength implements java.util.Comparator {

    public int compare(Object objIn, Object objOut) {
        // Defines the sequence by -/+ sign
        return (((String)objIn).length() - (((String)objOut).length()));
    }

}
Here is the expected output.

----- Unsorted List -----
Use primitive data types instead of objects as instance variables.
Avoid creating an object that is only for accessing a method.
Flatten objects to reduce the number of nested objects.
Preallocate storage for large collections of objects by mapping the instance variables into multiple arrays.
Use StringBuffer rather than the string concatenation operator (+).
Use methods that alter objects directly without making copies.
Create or use specific classes that handle primitive data types rather than wrapping the primitive data types.
Consider using a ThreadLocal to provide threaded access to singletons with state.
Use the final modifier on instance-variable definitions to create immutable internally accessible objects.
Use WeakReferences to hold elements in large canonical lookup tables.
Reduce object-creation bottlenecks by targeting the object-creation process.
Keep constructors simple and inheritance hierarchies shallow.
Avoid initializing instance variables more than once.

----- Alphabetic Sort List -----
Avoid creating an object that is only for accessing a method.
Avoid initializing instance variables more than once.
Consider using a ThreadLocal to provide threaded access to singletons with state.
Create or use specific classes that handle primitive data types rather than wrapping the primitive data types.
Flatten objects to reduce the number of nested objects.
Keep constructors simple and inheritance hierarchies shallow.
Preallocate storage for large collections of objects by mapping the instance variables into multiple arrays.
Reduce object-creation bottlenecks by targeting the object-creation process.
Use StringBuffer rather than the string concatenation operator (+).
Use WeakReferences to hold elements in large canonical lookup tables.
Use methods that alter objects directly without making copies.
Use primitive data types instead of objects as instance variables.
Use the final modifier on instance-variable definitions to create immutable internally accessible objects.

----- Sort By Line Length -----
Avoid initializing instance variables more than once.
Flatten objects to reduce the number of nested objects.
Avoid creating an object that is only for accessing a method.
Keep constructors simple and inheritance hierarchies shallow.
Use methods that alter objects directly without making copies.
Use primitive data types instead of objects as instance variables.
Use StringBuffer rather than the string concatenation operator (+).
Use WeakReferences to hold elements in large canonical lookup tables.
Reduce object-creation bottlenecks by targeting the object-creation process.
Consider using a ThreadLocal to provide threaded access to singletons with state.
Use the final modifier on instance-variable definitions to create immutable internally accessible objects.
Preallocate storage for large collections of objects by mapping the instance variables into multiple arrays.
Create or use specific classes that handle primitive data types rather than wrapping the primitive data types.
Warnings

  • ArrayList cannot hold prmitives. User wrapper classes (Integer, Double, etc...) instead.
  • For synchronized arrays use Vector instead.


Attached Thumbnails Attached Files

Submit "Java ArrayList : Generics & Sorting" to Facebook Submit "Java ArrayList : Generics & Sorting" to Digg Submit "Java ArrayList : Generics & Sorting" to del.icio.us Submit "Java ArrayList : Generics & Sorting" to StumbleUpon Submit "Java ArrayList : Generics & Sorting" to Google

Comments