Results 1 to 1 of 1
  1. #1
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    20

    Default Java ArrayList : Generics & Sorting



    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 Files Attached Files

Similar Threads

  1. Sorting ArrayList by object data
    By drymsza1234 in forum New To Java
    Replies: 2
    Last Post: 04-15-2010, 01:22 AM
  2. Sorting printed ArrayList of user inputted strings.
    By movsesinator in forum New To Java
    Replies: 3
    Last Post: 04-03-2010, 09:27 PM
  3. Sorting an ArrayList
    By flesh-bound-book in forum New To Java
    Replies: 3
    Last Post: 02-13-2010, 12:20 PM
  4. Replies: 2
    Last Post: 04-21-2008, 11:43 AM
  5. ArrayList<type> - Generics
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-14-2007, 03:21 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •