TreeSet and ArrayList

TreeSet implements SortedSet:- This class guarantees that the sorted set will be in ascending element order, sorted according to the natural order of the elements (see Comparable), or by the comparator provided at set creation time, depending on which constructor is used.
import java.util.Iterator;
import java.util.TreeSet;

public class TreeSetExample {

    public static void main(String[] args) {

        // TreeSet return in ordered elements
        TreeSet<String> ts=new TreeSet<String>();

        ts.add("b");
        ts.add("a");
        ts.add("d");
        ts.add("c");

        // get element in Iterator
        Iterator it=ts.iterator();

        // get descending order of elements
        //Iterator it=ts.descendingIterator();

        while(it.hasNext())
        {
          String value=(String)it.next();

          System.out.println("Value :"+value);
        }
    }
}
Output
TreeSet Value:a
TreeSet Value:b
TreeSet Value:c
TreeSet Value :d
 
ArrayList implements List Resizable:- Array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.


import java.util.ArrayList;
public class SimpleArrayListExample {

 public static void main(String[] args) {

//create an ArrayList object
 ArrayList arrayList = new ArrayList();

/*
Add elements to Arraylist using
boolean add(Object o) method. It returns true as a general behavior
of Collection.add method. The specified object is appended at the end
of the ArrayList.
*/
 arrayList.add("1");
arrayList.add("2");
 arrayList.add("3");

/*
Use get method of Java ArrayList class to display elements of ArrayList.
 Object get(int index) returns and element at the specified index in the ArrayList   
*/
System.out.println("Getting elements of ArrayList");
System.out.println(arrayList.get(0));
System.out.println(arrayList.get(1));
System.out.println(arrayList.get(2));
}
}

/*
Output would be
Getting elements of ArrayList
1
2
1.3
*/

ArrayList class provides methods for basic array operations:- 

  • add( Object o ) - puts reference to object into ArrayList
  • get( int index ) - retrieves object reference from ArrayList index position
  • size() - returns ArrayList size
  • remove( int index ) - removes the element at the specified position in this list. Shifts any subsequent elements to the left and returns the element that was removed from the list.
  • indexOf( Object o) - finds the index in this list of the first occurrence of the specified element
  • clear() - removes all of the elements

People who read this post also read :



Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More