zondag 20 maart 2011

[Java] Basics of Collections

Java Collections

In this small tutorial, I'll give you some examples on how to use most of the collections in Java. I'm not going in too much detail, I'll just give a brief overview of some nice collections and why you should use them.

Here's the class diagram of the collections. I'll add a Map to that too, which the implementations HashMap and TreeMap, similar to the Set implementations.

[Image: map2.JPG]

List<E>

This is the basic interface for Lists. I mainly use the ArrayList, there's of course also the LinkedList and Vector


Code:
List myList;
myList = new ArrayList(); //create an ArrayList
myList = new LinkedList(); //create a LinkedList

Set

Now, we've got Set, with the extended class SortedSet.
HashSet would be an implementation of Set, and TreeSet one of SortedSet.
Just remember, TreeSet = Sorted



Code:
Set<String> mySet = new HashSet<String>(myList);

Map<k,v>

A Map might be very handy, if you want to store data with a key. For example, we could could store a class "Car" with the key "licensePlate". Or, idNumber, and personal data.

A SortedMap is sorted Interface which implements Set. An implementation of SortedMap would be TreeMap.
Remember, TreeMap = Sorted



Code:
Map<int, String> myMap = new HashMap<int,String>(); //int as key, String as value
myMap.put(1, "Qkyrie"); //put Qkyrie as value, with key 1
myMap.put(2, "Ben121");
myMap.put(3, "SB");
String myName = myMap.get(1) //would place "Qkyrie" in myName.

Properties

A propertiestable could come quite in handy when defining properties for a program. An example is given below.


Code:
//declare property
Properties table = new Properties();

//set properties
table.setProperty("color", "blue");
table.setProperty("programname, "Qryptonite");

//navigate through all properties with a set
Set<Object> keys = table.keySet();
for(Object key: keys)
table.getProperty((String) key);

Iterators

Using Iterators is the best way for navigating through a collection.
some examples are given below:


Print a List Reversed

Code:
private void printReversedList(List<String> list)
{
ListIterator<String> iterator = list.listIterator( list.size() );
System.out.println("\nReversed List:");

while(iterator.hasPrevious() )
System.out.printf("%s", iterator.previous() );
}

Convert a List of Strings all to uppercase.

Code:
private void convertToUppercaseStrings(List<String> list)
{
ListIterator<String> iterator = list.ListIterator();

while( iterator.hasNext() )
{
String color = iterator.next(); //remember, if this wasn't a string -> downcast
iterator.set(color.toUpperCase() );

}//end while
}//end method

ending
If you want some more examples on any collections or Arrays, feel free to ask.

@_Qkyrie_

Geen opmerkingen:

Een reactie posten