,"Java's
The
class deserves a little explanation on its own. In the text on the
interface the
class is listed as an implementation. The typical use of a
is not as a
though.
A
is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again. This is also referred to as the "Last In First Out (LIFO)" principle. In contrast, a
uses a "First In First Out (FIFO)" principle.
's are really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.
Here is a
usage example:
Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); //look at top object ("3"), without taking it off the stack. Object objTop = stack.peek(); Object obj3 = stack.pop(); //the string "3" is at the top of the stack. Object obj2 = stack.pop(); //the string "2" is at the top of the stack. Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
The
method pushes an object onto the top of the
.
The
method returns the object at the top of the
, but leaves the object on of the
.
The
method returns the object at the top of the stack
, and removes the object from the
.
The
class deserves a little explanation on its own. In the text on the
interface the
class is listed as an implementation. The typical use of a
is not as a
though.
A
is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again. This is also referred to as the "Last In First Out (LIFO)" principle. In contrast, a
uses a "First In First Out (FIFO)" principle.
's are really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.
Here is a
usage example:
Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); //look at top object ("3"), without taking it off the stack. Object objTop = stack.peek(); Object obj3 = stack.pop(); //the string "3" is at the top of the stack. Object obj2 = stack.pop(); //the string "2" is at the top of the stack. Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
The
method pushes an object onto the top of the
.
The
method returns the object at the top of the
, but leaves the object on of the
.
The
method returns the object at the top of the stack
, and removes the object from the
.
The
class deserves a little explanation on its own. In the text on the
interface the
class is listed as an implementation. The typical use of a
is not as a
though.
A
is a data structure where you add elements to the "top" of the stack, and also remove elements from the top again. This is also referred to as the "Last In First Out (LIFO)" principle. In contrast, a
uses a "First In First Out (FIFO)" principle.
's are really handy for some types of data processing, for instance if you are parsing an XML file using either SAX or StAX. For an example, see my Java SAX Example in my Java XML tutorial.
Here is a
usage example:
Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); //look at top object ("3"), without taking it off the stack. Object objTop = stack.peek(); Object obj3 = stack.pop(); //the string "3" is at the top of the stack. Object obj2 = stack.pop(); //the string "2" is at the top of the stack. Object obj1 = stack.pop(); //the string "1" is at the top of the stack.
The
method pushes an object onto the top of the
.
The
method returns the object at the top of the
, but leaves the object on of the
.
The
method returns the object at the top of the stack
, and removes the object from the
.
You can search for an object on the stack to get it's index, using the
method. The object's equals()
method is called on every object on the
to determine if the searched-for object is present on the
. The index you get is the index from the top of the
, meaning the top element on the
has index 1.
Here is how you search a
for an object:
Stack stack = new Stack(); stack.push("1"); stack.push("2"); stack.push("3"); int index = stack.search("3"); //index = 3","Stack","java.util.Stack","class",1 ,"Java's
The
interface is a subtype of the
interface. It has a few extensions to the
which makes it possible to navigate the map. I will take a closer look at these navigation methods in this text.
The java.util
package only has one implementation of the
interface:
. There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It has a few extensions to the
which makes it possible to navigate the map. I will take a closer look at these navigation methods in this text.
The java.util
package only has one implementation of the
interface:
. There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It has a few extensions to the
which makes it possible to navigate the map. I will take a closer look at these navigation methods in this text.
The java.util
package only has one implementation of the
interface:
. There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It has a few extensions to the
which makes it possible to navigate the map. I will take a closer look at these navigation methods in this text.
The java.util
package only has one implementation of the
interface:
. There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The first interesting navigation methods are the
and
methods.
The
method returns a
in which the order of the elements is reversed compared to the original key set. The returned "view" is backed by the original
ket set, so changes to the descending set are also reflected in the original set. However, you should not remove elements directly from the key set. Use the
method instead.
Here is a simple example:
NavigableSet reverse = map.descendingKeySet();
The
method returns a
which is a view of the original
. The order of the elements in this view map is reverse of the order of the original map. Being a view of the original map, any changes to this view is also reflected in the original map.
Here is a simple example:
NavigableMap descending = map.descendingMap();","NavigableMap","java.util.NavigableMap","class",1 ,"Java's
The first interesting navigation methods are the
and
methods.
The
method returns a
in which the order of the elements is reversed compared to the original key set. The returned "view" is backed by the original
ket set, so changes to the descending set are also reflected in the original set. However, you should not remove elements directly from the key set. Use the
method instead.
Here is a simple example:
NavigableSet reverse = map.descendingKeySet();
The
method returns a
which is a view of the original
. The order of the elements in this view map is reverse of the order of the original map. Being a view of the original map, any changes to this view is also reflected in the original map.
Here is a simple example:
NavigableMap descending = map.descendingMap();","NavigableSet","java.util.NavigableSet","class",1 ,"Java's
The first interesting navigation methods are the
and
methods.
The
method returns a
in which the order of the elements is reversed compared to the original key set. The returned "view" is backed by the original
ket set, so changes to the descending set are also reflected in the original set. However, you should not remove elements directly from the key set. Use the
method instead.
Here is a simple example:
NavigableSet reverse = map.descendingKeySet();
The
method returns a
which is a view of the original
. The order of the elements in this view map is reverse of the order of the original map. Being a view of the original map, any changes to this view is also reflected in the original map.
Here is a simple example:
NavigableMap descending = map.descendingMap();","Map","java.util.Map","class",0 ,"Java's
The
method returns a view of the original
which only contains elements that are "less than" the given element. Here is an example:
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //this headmap1 will contain "1" and "2" SortedMap headmap1 = original.headMap("3"); //this headmap2 will contain "1", "2", and "3" because "inclusive"=true NavigableMap headmap2 = original.headMap("3", true);
The
method works the same way, except it returns all elements that are higher than the given parameter element.
The
allows you to pass two parameters demarcating the boundaries of the view map to return. Here is an example:
NavigableMap original = new TreeMap(); original.put("1", "1"); original.add("2", "2"); original.add("3", "3"); original.add("4", "4"); original.add("5", "5"); //this submap1 will contain "3", "3" SortedMap submap1 = original.subMap("2", "4"); //this submap2 will contain ("2", "2") ("3", "3") and ("4", "4") because // fromInclusive=true, and toInclusive=true NavigableMap submap2 = original.subMap("2", true, "4", true);","NavigableMap","java.util.NavigableMap","class",1 ,"Java's
The
method returns the least (smallest) key in this map that is greater than or equal to the element passed as parameter to the
method. Here is an example:
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //ceilingKey will be "2". Object ceilingKey = original.ceilingKey("2"); //floorKey will be "2". Object floorKey = original.floorKey("2");
The
method does the opposite of
The
method returns the least (smallest) element in this map that is greater than (not equal too) the element passed as parameter to the
method. Here is an example:
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //higherKey will be "3". Object higherKey = original.higherKey("2"); //lowerKey will be "1" Object lowerKey = original.lowerKey("2");
The
method does the opposite of the
method.
The
also has methods to get the entry for a given key, rather than the key itself. These methods behave like the
etc. methods, except they return an
instead of the key object itself.
A
maps a single key to a single value.
Here is a simple example. For more details, check out the JavaDoc.
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //higherEntry will be ("3", "3"). Map.Entry higherEntry = original.higherEntry("2"); //lowerEntry will be ("1", "1") Map.Entry lowerEntry = original.lowerEntry("2");","NavigableMap","java.util.NavigableMap","class",0 ,"Java's
The
also has methods to get the entry for a given key, rather than the key itself. These methods behave like the
etc. methods, except they return an
instead of the key object itself.
A
maps a single key to a single value.
Here is a simple example. For more details, check out the JavaDoc.
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //higherEntry will be ("3", "3"). Map.Entry higherEntry = original.higherEntry("2"); //lowerEntry will be ("1", "1") Map.Entry lowerEntry = original.lowerEntry("2");","Entry","java.util.Map.Entry","class",0 ,"Java's
The
method returns and removes the "first" entry (key + value) in the
or null if the map is empty. The
returns and removes the "last" element in the map or null if the map is empty. "First" means smallest element according to the sort order of the keys. "Last" means largest key according to the element sorting order of the map.
Here are two examples:
NavigableMap original = new TreeMap(); original.put("1", "1"); original.put("2", "2"); original.put("3", "3"); //first is ("1", "1") Map.Entry first = original.pollFirstEntry(); //last is ("3", "3") Map.Entry last = original.pollLastEntry();","NavigableMap","java.util.NavigableMap","class",1 ,"Java's
There are still a few interesting methods left in the
interface that I have not covered here. For instance, the
and
methods. You can check out these last methods in the official JavaDoc.
The
interface is a subtype of the
interface. It represents an ordered list of objects, meaning you can access the elements of a
in a specific order, and by an index too. You can also add the same element more than once to a
.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It represents an ordered list of objects, meaning you can access the elements of a
in a specific order, and by an index too. You can also add the same element more than once to a
.
Here is a list of the topics covered in this text:
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
List listA = new ArrayList(); List listB = new LinkedList(); List listC = new Vector(); List listD = new Stack();","Collection","java.util.Collection","class",0 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
List listA = new ArrayList(); List listB = new LinkedList(); List listC = new Vector(); List listD = new Stack();","List","java.util.List","class",0 ,"Java's
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
List listA = new ArrayList(); listA.add("element 1"); listA.add("element 2"); listA.add("element 3"); listA.add(0, "element 0");
The first three
calls add a
instance to the end of the list. The last
call adds a
at index 0, meaning at the beginning of the list.
The order in which the elements are added to the
is stored, so you can access the elements in the same order. You can do so using either the
method, or via the
returned by the
method. Here is how:
List listA = new ArrayList(); listA.add("element 0"); listA.add("element 1"); listA.add("element 2"); //access via index String element0 = listA.get(0); String element1 = listA.get(1); String element3 = listA.get(2); //access via Iterator Iterator iterator = listA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : listA) { String element = (String) object; }
When iterating the list via its
or via the for-loop (which also uses the Iterator behind the scene), the elements are iterated in the same sequence they are stored in the list.
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
List listA = new ArrayList(); listA.add("element 1"); listA.add("element 2"); listA.add("element 3"); listA.add(0, "element 0");
The first three
calls add a
instance to the end of the list. The last
call adds a
at index 0, meaning at the beginning of the list.
The order in which the elements are added to the
is stored, so you can access the elements in the same order. You can do so using either the
method, or via the
returned by the
method. Here is how:
List listA = new ArrayList(); listA.add("element 0"); listA.add("element 1"); listA.add("element 2"); //access via index String element0 = listA.get(0); String element1 = listA.get(1); String element3 = listA.get(2); //access via Iterator Iterator iterator = listA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : listA) { String element = (String) object; }
When iterating the list via its
or via the for-loop (which also uses the Iterator behind the scene), the elements are iterated in the same sequence they are stored in the list.
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
List listA = new ArrayList(); listA.add("element 1"); listA.add("element 2"); listA.add("element 3"); listA.add(0, "element 0");
The first three
calls add a
instance to the end of the list. The last
call adds a
at index 0, meaning at the beginning of the list.
The order in which the elements are added to the
is stored, so you can access the elements in the same order. You can do so using either the
method, or via the
returned by the
method. Here is how:
List listA = new ArrayList(); listA.add("element 0"); listA.add("element 1"); listA.add("element 2"); //access via index String element0 = listA.get(0); String element1 = listA.get(1); String element3 = listA.get(2); //access via Iterator Iterator iterator = listA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : listA) { String element = (String) object; }
When iterating the list via its
or via the for-loop (which also uses the Iterator behind the scene), the elements are iterated in the same sequence they are stored in the list.
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
List listA = new ArrayList(); listA.add("element 1"); listA.add("element 2"); listA.add("element 3"); listA.add(0, "element 0");
The first three
calls add a
instance to the end of the list. The last
call adds a
at index 0, meaning at the beginning of the list.
The order in which the elements are added to the
is stored, so you can access the elements in the same order. You can do so using either the
method, or via the
returned by the
method. Here is how:
List listA = new ArrayList(); listA.add("element 0"); listA.add("element 1"); listA.add("element 2"); //access via index String element0 = listA.get(0); String element1 = listA.get(1); String element3 = listA.get(2); //access via Iterator Iterator iterator = listA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : listA) { String element = (String) object; }
When iterating the list via its
or via the for-loop (which also uses the Iterator behind the scene), the elements are iterated in the same sequence they are stored in the list.
You can remove elements in two ways:
removes that element in the list, if it is present. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.
removes the element at the given index. All subsequent elements in the list are then moved up in the list. Their index thus decreases by 1.
By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
List<MyObject> list = new ArrayList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = list.get(0); for(MyObject anObject : list){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Object","java.lang.Object","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
List<MyObject> list = new ArrayList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = list.get(0); for(MyObject anObject : list){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","List","java.util.List","class",0 ,"Java's There is a lot more you can do with a
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the elements.
In order to understand and use the Java Collections API effectively it is useful to have an overview of the interfaces it contains. So, that is what I will provide here.
There are two "groups" of interfaces:
's and
's.
Here is a graphical overview of the
interface hierarchy:
And here is a graphical overview of the
interface hierarchy:
You can find links to explanations of most (if not all) of these interfaces and implementations in the sub-menu at the top right of this page. That top-menu exists on all pages in this trail.
","Collections","java.util.Collections","class",0 ,"JavaIn order to understand and use the Java Collections API effectively it is useful to have an overview of the interfaces it contains. So, that is what I will provide here.
There are two "groups" of interfaces:
's and
's.
Here is a graphical overview of the
interface hierarchy:
And here is a graphical overview of the
interface hierarchy:
You can find links to explanations of most (if not all) of these interfaces and implementations in the sub-menu at the top right of this page. That top-menu exists on all pages in this trail.
","Collection","java.util.Collection","class",0 ,"JavaIn order to understand and use the Java Collections API effectively it is useful to have an overview of the interfaces it contains. So, that is what I will provide here.
There are two "groups" of interfaces:
's and
's.
Here is a graphical overview of the
interface hierarchy:
And here is a graphical overview of the
interface hierarchy:
You can find links to explanations of most (if not all) of these interfaces and implementations in the sub-menu at the top right of this page. That top-menu exists on all pages in this trail.
","Map","java.util.Map","class",0 ,"Java's The
interface (
) is one of the root interfaces of the Java collection classes. The
interface extends
, so all subtypes of
also implement the
interface.
A class that implements the
can be used with the new for-loop. Here is such an example:
List list = new ArrayList(); for(Object o : list){ //do something o; }
The
interface has only one method:
public interface Iterable<T> { public Iterator<T> iterator(); }
How you implement this
interface so that you can use it with the new for-loop, is explained in the text Implementing the Iterable Interface, in my Java Generics tutorial.
The
interface (
) is one of the root interfaces of the Java collection classes. The
interface extends
, so all subtypes of
also implement the
interface.
A class that implements the
can be used with the new for-loop. Here is such an example:
List list = new ArrayList(); for(Object o : list){ //do something o; }
The
interface has only one method:
public interface Iterable<T> { public Iterator<T> iterator(); }
How you implement this
interface so that you can use it with the new for-loop, is explained in the text Implementing the Iterable Interface, in my Java Generics tutorial.
You can sort
collections using the
method. You can sort these two types of
's.
You can sort
collections using the
method. You can sort these two types of
's.
To sort a
you do this:
List list = new ArrayList(); //add elements to the list Collections.sort(list);
When sorting a list like this the elements are ordered according to their "natural order". For objects to have a natural order they must implement the interface
. In other words, the objects must be comparable to determine their order. Here is how the
interface looks:
public interface Comparable<T> { int compareTo(T o); }
The
method should compare this object to another object, return an int
value. Here are the rules for that int
value:
There are a few more specific rules to obey in the implementation, but the above is the primary requirements. Check out the JavaDoc for the details.
","List","java.util.List","class",0 ,"Sorting Java Collections","Sorting Objects by their Natural Order"," To sort a
you do this:
List list = new ArrayList(); //add elements to the list Collections.sort(list);
When sorting a list like this the elements are ordered according to their "natural order". For objects to have a natural order they must implement the interface
. In other words, the objects must be comparable to determine their order. Here is how the
interface looks:
public interface Comparable<T> { int compareTo(T o); }
The
method should compare this object to another object, return an int
value. Here are the rules for that int
value:
There are a few more specific rules to obey in the implementation, but the above is the primary requirements. Check out the JavaDoc for the details.
","Comparable","java.lang.Comparable","class",1 ,"Sorting Java Collections","Sorting Objects by their Natural Order - part 2"," Let's say you are sorting a
of
elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the
method.
When you implement the
method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee
objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.
Let's say you are sorting a
of
elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the
method.
When you implement the
method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee
objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.
Let's say you are sorting a
of
elements. To sort them, each string is compared to the others according to some sorting algorithm (not interesting here). Each string compares itself to another string by alphabetic comparison. So, if a string is less than another string by alphabetic comparison it will return a negative number from the
method.
When you implement the
method in your own classes you will have to decide how these objects should be compared to each other. For instance, Employee
objects can be compared by their first name, last name, salary, start year or whatever else you think makes sense.
Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a
instead. Here is how you sort a list using a
:
List list = new ArrayList(); //add elements to the list Comparator comparator = new SomeComparator(); Collections.sort(list, comparator);
Notice how the
method now takes a
as parameter in addition to the
. This
compares the elements in the list two by two. Here is how the
interface looks:
public interface Comparator<T> { int compare(T object1, T object2); }
The
method compares two objects to each other and should:
There are a few more requirements to the implementation of the
method, but these are the primary requirements. Check out the JavaDoc for more specific details.
Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a
instead. Here is how you sort a list using a
:
List list = new ArrayList(); //add elements to the list Comparator comparator = new SomeComparator(); Collections.sort(list, comparator);
Notice how the
method now takes a
as parameter in addition to the
. This
compares the elements in the list two by two. Here is how the
interface looks:
public interface Comparator<T> { int compare(T object1, T object2); }
The
method compares two objects to each other and should:
There are a few more requirements to the implementation of the
method, but these are the primary requirements. Check out the JavaDoc for more specific details.
Sometimes you may want to sort a list according to another order than their natural order. Perhaps the objects you are sorting do not even have a natural order. In that case you can use a
instead. Here is how you sort a list using a
:
List list = new ArrayList(); //add elements to the list Comparator comparator = new SomeComparator(); Collections.sort(list, comparator);
Notice how the
method now takes a
as parameter in addition to the
. This
compares the elements in the list two by two. Here is how the
interface looks:
public interface Comparator<T> { int compare(T object1, T object2); }
The
method compares two objects to each other and should:
There are a few more requirements to the implementation of the
method, but these are the primary requirements. Check out the JavaDoc for more specific details.
Here is an example
that compares two fictive Employee objects:
public class MyComparator<Employee> implements Comparator<Employee> { public int compare(Employee emp1, Employee emp2){ if(emp1.getSalary() < emp2.getSalary()) return -1; if(emp1.getSalary() == emp2.getSalary()) return 0; return 1; } }
A shorter way to write the comparison would be like this:
public class MyComparator<Employee> implements Comparator<Employee> { public int compare(Employee emp1, Employee emp2){ return emp1.getSalary() - emp2.getSalary(); } }
By subtracting one salary from the other, the resulting value is automatically either negative, 0 or positive. Smart, right?
If you want to compare objects by more than one factor, start by comparing by the first factor (e.g first name). Then, if the first factors are equal, compare by the second factor (e.g. last name, or salary) etc.
","Comparator","java.util.Comparator","class",0 ,"Java's The
interface represents a mapping between a key and a value. The
interface is not a subtype of the
interface. Therefore it behaves a bit different from the rest of the collection types.
Here is a list of the topics covered in this text:
The
interface represents a mapping between a key and a value. The
interface is not a subtype of the
interface. Therefore it behaves a bit different from the rest of the collection types.
Here is a list of the topics covered in this text:
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
In my experience, the most commonly used
implementations are
and
.
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the maps.
maps a key and a value. It does not guarantee any order of the elements stored internally in the map.
also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values. Check out the JavaDoc for more details.
Here are a few examples of how to create a
instance:
Map mapA = new HashMap(); Map mapB = new TreeMap();","Map","java.util.Map","class",1 ,"Java's
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
In my experience, the most commonly used
implementations are
and
.
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the maps.
maps a key and a value. It does not guarantee any order of the elements stored internally in the map.
also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values. Check out the JavaDoc for more details.
Here are a few examples of how to create a
instance:
Map mapA = new HashMap(); Map mapB = new TreeMap();","HashMap","java.util.HashMap","class",1 ,"Java's
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
In my experience, the most commonly used
implementations are
and
.
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the maps.
maps a key and a value. It does not guarantee any order of the elements stored internally in the map.
also maps a key and a value. Furthermore it guarantees the order in which keys or values are iterated - which is the sort order of the keys or values. Check out the JavaDoc for more details.
Here are a few examples of how to create a
instance:
Map mapA = new HashMap(); Map mapB = new TreeMap();","TreeMap","java.util.TreeMap","class",1 ,"Java's
To add elements to a
you call its
method. Here are a few examples:
Map mapA = new HashMap(); mapA.put("key1", "element 1"); mapA.put("key2", "element 2"); mapA.put("key3", "element 3");
The three
calls maps a string value to a string key. You can then obtain the value using the key. To do that you use the
method like this:
String element1 = (String) mapA.get("key1");
You can iterate either the keys or the values of a
. Here is how you do that:
// key iterator Iterator iterator = mapA.keySet().iterator(); // value iterator Iterator iterator = mapA.values();
Most often you iterate the keys of the
and then get the corresponding values during the iteration. Here is how it looks:
Iterator iterator = mapA.keySet().iterator(); while(iterator.hasNext(){ Object key = iterator.next(); Object value = mapA.get(key); } //access via new for-loop for(Object key : mapA.keySet()) { Object value = mapA.get(key); }","Map","java.util.Map","class",1 ,"Java's
You remove elements by calling the
method. You thus remove the (key, value) pair matching the key.
By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a
. Here is an example:
Map<String, MyObject> map = new HashSet<String, MyObject>();
This
can now only accept
objects for keys, and MyObject
instances for values. You can then access and iterate keys and values without casting them. Here is how it looks:
for(MyObject anObject : map.values()){ //do someting to anObject... } for(String key : map.keySet()){ MyObject value = map.get(key); //do something to value }
For more information about Java Generics, see the Java Generics Tutorial.
","Object","java.lang.Object","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a
. Here is an example:
Map<String, MyObject> map = new HashSet<String, MyObject>();
This
can now only accept
objects for keys, and MyObject
instances for values. You can then access and iterate keys and values without casting them. Here is how it looks:
for(MyObject anObject : map.values()){ //do someting to anObject... } for(String key : map.keySet()){ MyObject value = map.get(key); //do something to value }
For more information about Java Generics, see the Java Generics Tutorial.
","Map","java.util.Map","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can use for both keys and values in a
. Here is an example:
Map<String, MyObject> map = new HashSet<String, MyObject>();
This
can now only accept
objects for keys, and MyObject
instances for values. You can then access and iterate keys and values without casting them. Here is how it looks:
for(MyObject anObject : map.values()){ //do someting to anObject... } for(String key : map.keySet()){ MyObject value = map.get(key); //do something to value }
For more information about Java Generics, see the Java Generics Tutorial.
","String","java.lang.String","class",0 ,"Java's There is more you can do with a
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the keys and values.
The
interface is a subtype of the
interface. It represents set of objects, meaning each element can only exists once in a
.
Table of contents:
The
interface is a subtype of the
interface. It represents set of objects, meaning each element can only exists once in a
.
Table of contents:
Here is first a simple Java
example to give you a feel for how sets work:
Set setA = new HashSet(); String element = "element 1"; setA.add(element); System.out.println( set.contains(element) );
This example creates a
which is one of the classes in the Java APIs that implement the
interface. Then it adds a string object to the set, and finally it checks if the set contains the element just added.
Here is first a simple Java
example to give you a feel for how sets work:
Set setA = new HashSet(); String element = "element 1"; setA.add(element); System.out.println( set.contains(element) );
This example creates a
which is one of the classes in the Java APIs that implement the
interface. Then it adds a string object to the set, and finally it checks if the set contains the element just added.
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the sets.
is backed by a
. It makes no guarantees about the sequence of the elements when you iterate them.
differs from
by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the
. Reinserting an element that is already in the
does not change this order.
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the sets.
is backed by a
. It makes no guarantees about the sequence of the elements when you iterate them.
differs from
by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the
. Reinserting an element that is already in the
does not change this order.
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the sets.
is backed by a
. It makes no guarantees about the sequence of the elements when you iterate them.
differs from
by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the
. Reinserting an element that is already in the
does not change this order.
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the sets.
is backed by a
. It makes no guarantees about the sequence of the elements when you iterate them.
differs from
by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the
. Reinserting an element that is already in the
does not change this order.
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
Each of these
implementations behaves a little differently with respect to the order of the elements when iterating the
, and the time (big O notation) it takes to insert and access elements in the sets.
is backed by a
. It makes no guarantees about the sequence of the elements when you iterate them.
differs from
by guaranteeing that the order of the elements during iteration is the same as the order they were inserted into the
. Reinserting an element that is already in the
does not change this order.
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","TreeSet","java.util.TreeSet","class",1 ,"Java's
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","Collections","java.util.Collections","class",0 ,"Java's
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","List","java.util.List","class",0 ,"Java's
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","Comparable","java.lang.Comparable","class",0 ,"Java's
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","Comparator","java.util.Comparator","class",0 ,"Java's
also guarantees the order of the elements when iterated, but the order is the sorting order of the elements. In other words, the order in which the elements whould be sorted if you used a
on a
or array containing these elements. This order is determined either by their natural order (if they implement
), or by a specific
implementation.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Set setA = new EnumSet(); Set setB = new HashSet(); Set setC = new LinkedHashSet(); Set setD = new TreeSet();","Set","java.util.Set","class",0 ,"Java's
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Set setA = new HashSet(); setA.add("element 1"); setA.add("element 2"); setA.add("element 3");
The three
calls add a
instance to the set.
When iterating the elements in the
the order of the elements depends on what
implementation you use, as mentioned earlier. Here is an iteration example:
Set setA = new HashSet(); setA.add("element 0"); setA.add("element 1"); setA.add("element 2"); //access via Iterator Iterator iterator = setA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : setA) { String element = (String) object; }","Set","java.util.Set","class",1 ,"Java's
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Set setA = new HashSet(); setA.add("element 1"); setA.add("element 2"); setA.add("element 3");
The three
calls add a
instance to the set.
When iterating the elements in the
the order of the elements depends on what
implementation you use, as mentioned earlier. Here is an iteration example:
Set setA = new HashSet(); setA.add("element 0"); setA.add("element 1"); setA.add("element 2"); //access via Iterator Iterator iterator = setA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : setA) { String element = (String) object; }","Collection","java.util.Collection","class",0 ,"Java's
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Set setA = new HashSet(); setA.add("element 1"); setA.add("element 2"); setA.add("element 3");
The three
calls add a
instance to the set.
When iterating the elements in the
the order of the elements depends on what
implementation you use, as mentioned earlier. Here is an iteration example:
Set setA = new HashSet(); setA.add("element 0"); setA.add("element 1"); setA.add("element 2"); //access via Iterator Iterator iterator = setA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : setA) { String element = (String) object; }","String","java.lang.String","class",0 ,"Java's
You remove elements by calling the
method. There is no way to remove an object based on index in a
, since the order of the elements depends on the
implementation.
By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Set<MyObject> set = new HashSet<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
for(MyObject anObject : set){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Object","java.lang.Object","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Set<MyObject> set = new HashSet<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
for(MyObject anObject : set){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Set","java.util.Set","class",0 ,"Java's There is a lot more you can do with a
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the elements.
The
interface is a subtype of the
interface. It represents an ordered list of objects just like a
, but its intended use is slightly different. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. Just like a queue in a supermarket.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It represents an ordered list of objects just like a
, but its intended use is slightly different. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. Just like a queue in a supermarket.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It represents an ordered list of objects just like a
, but its intended use is slightly different. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. Just like a queue in a supermarket.
Here is a list of the topics covered in this text:
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","Collection","java.util.Collection","class",0 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","Queue","java.util.Queue","class",1 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","LinkedList","java.util.LinkedList","class",0 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","PriorityQueue","java.util.PriorityQueue","class",1 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","Comparable","java.lang.Comparable","class",0 ,"Java's
Being a
subtype all methods in the
interface are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard queue implementation.
stores its elements internally according to their natural order (if they implement
), or according to a
passed to the
.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Queue queueA = new LinkedList(); Queue queueB = new PriorityQueue();","Comparator","java.util.Comparator","class",0 ,"Java's
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Queue queueA = new LinkedList(); queueA.add("element 1"); queueA.add("element 2"); queueA.add("element 3");
The order in which the elements added to the
are stored internally, depends on the implementation. The same is true for the order in which elements are retrieved from the queue. You should consult the JavaDoc's for more information about the specific
implementations.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the
method. Here is how that looks:
Object firstElement = queueA.element();
To take the first element out of the queue, you use the
method which is described later.
You can also iterate all elements of a queue, instead of just processing one at a time. Here is how that looks:
Queue queueA = new LinkedList(); queueA.add("element 0"); queueA.add("element 1"); queueA.add("element 2"); //access via Iterator Iterator iterator = queueA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : queueA) { String element = (String) object; }
When iterating the queue via its
or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Queue queueA = new LinkedList(); queueA.add("element 1"); queueA.add("element 2"); queueA.add("element 3");
The order in which the elements added to the
are stored internally, depends on the implementation. The same is true for the order in which elements are retrieved from the queue. You should consult the JavaDoc's for more information about the specific
implementations.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the
method. Here is how that looks:
Object firstElement = queueA.element();
To take the first element out of the queue, you use the
method which is described later.
You can also iterate all elements of a queue, instead of just processing one at a time. Here is how that looks:
Queue queueA = new LinkedList(); queueA.add("element 0"); queueA.add("element 1"); queueA.add("element 2"); //access via Iterator Iterator iterator = queueA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : queueA) { String element = (String) object; }
When iterating the queue via its
or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.
To add elements to a
you call its
method. This method is inherited from the
interface. Here are a few examples:
Queue queueA = new LinkedList(); queueA.add("element 1"); queueA.add("element 2"); queueA.add("element 3");
The order in which the elements added to the
are stored internally, depends on the implementation. The same is true for the order in which elements are retrieved from the queue. You should consult the JavaDoc's for more information about the specific
implementations.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the
method. Here is how that looks:
Object firstElement = queueA.element();
To take the first element out of the queue, you use the
method which is described later.
You can also iterate all elements of a queue, instead of just processing one at a time. Here is how that looks:
Queue queueA = new LinkedList(); queueA.add("element 0"); queueA.add("element 1"); queueA.add("element 2"); //access via Iterator Iterator iterator = queueA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : queueA) { String element = (String) object; }
When iterating the queue via its
or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the queue implementation.
To remove elements from a queue, you call the
method. This method removes the element at the head of the queue. In most
implementations the head and tail of the queue are at opposite ends. It is possible, however, to implement the
interface so that the head and tail of the queue is in the same end. In that case you would have a stack.
Here is a remove example();
Object firstElement = queueA.remove();","Queue","java.util.Queue","class",1 ,"Java's
By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Queue<MyObject> queue = new LinkedList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = queue.remove(); for(MyObject anObject : queue){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Object","java.lang.Object","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Queue<MyObject> queue = new LinkedList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = queue.remove(); for(MyObject anObject : queue){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Queue","java.util.Queue","class",0 ,"Java's There is a lot more you can do with a
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the elements.
equals()
is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList(); list.add("123"); boolean contains123 = list.contains("123");
The
iterates all its elements and execute "123".equals(element)
to determine if the element is equal to the parameter object "123". It is the
implementation that determines if two strings are equal.
The equals()
method is also used when removing elements. For instance:
List list = new ArrayList(); list.add("123"); boolean removed = list.remove("123");
The
again iterates all its elements and execute "123".equals(element)
to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.
As you can see, a proper implementation of .equals()
is essential for your own classes to work well with the Java Collection classes. So how do you implement equals()
"properly"?
equals()
is used in most collections to determine if a collection contains a given element. For instance:
List list = new ArrayList(); list.add("123"); boolean contains123 = list.contains("123");
The
iterates all its elements and execute "123".equals(element)
to determine if the element is equal to the parameter object "123". It is the
implementation that determines if two strings are equal.
The equals()
method is also used when removing elements. For instance:
List list = new ArrayList(); list.add("123"); boolean removed = list.remove("123");
The
again iterates all its elements and execute "123".equals(element)
to determine if the element is equal to the parameter object "123". The first element it finds that is equal to the given parameter "123" is removed.
As you can see, a proper implementation of .equals()
is essential for your own classes to work well with the Java Collection classes. So how do you implement equals()
"properly"?
The hashCode()
method of objects is used when you insert them into a HashTable
,
or
. If you do not know the theory of how a hashtable works internally, you can read about hastables on Wikipedia.org.
When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals()
method to find the right key. Once the right key is found, the object stored for that key is returned.
The hashCode()
method of objects is used when you insert them into a HashTable
,
or
. If you do not know the theory of how a hashtable works internally, you can read about hastables on Wikipedia.org.
When inserting an object into a hastable you use a key. The hash code of this key is calculated, and used to determine where to store the object internally. When you need to lookup an object in a hashtable you also use a key. The hash code of this key is calculated and used to determine where to search for the object.
The hash code only points to a certain "area" (or list, bucket etc) internally. Since different key objects could potentially have the same hash code, the hash code itself is no guarantee that the right key is found. The hashtable then iterates this area (all keys with the same hash code) and uses the key's equals()
method to find the right key. Once the right key is found, the object stored for that key is returned.
The Java Collections API's provide Java developers with a set of classes and interfaces that makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, except their size can change dynamically, and they have more advanced behaviour than arrays.
Rather than having to write your own collection classes, Java provides these ready-to-use collection classes for you. This tutorial will look closer at the Java Collection's, as they are also sometimes referred to, and more specifically the Java Collections available in Java 6.
The purpose of this tutorial is to give you an overview of the Java Collection classes. Thus it will not describe each and every little detail of the Java Collection classes. But, once you have an overview of what is there, it is much easier to read the rest in the JavaDoc's afterwards.
","Collections","java.util.Collections","class",0 ,"JavaThe fifth text in this Java Collections tutorial covers how to use Generics in Java Collections. Generics is very useful when working with Java's Collection classes.
","Collections","java.util.Collections","class",0 ,"Java The last two texts in this Java Collections tutorial explains the central role the two
methods equals()
and hashCode()
play when using Java Collections. You should read this, if you plan to use Java Collections with your own classes, and thus need to implement equals()
and hashCode()
.
The last two texts in this Java Collections tutorial explains the central role the two
methods equals()
and hashCode()
play when using Java Collections. You should read this, if you plan to use Java Collections with your own classes, and thus need to implement equals()
and hashCode()
.
The
interface is a subtype of the
interface. It represents a queue where you can insert and remove elements from both ends of the queue. Thus, "Deque" is short for "Double Ended Queue" and is pronounced "deck", like a deck of cards.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It represents a queue where you can insert and remove elements from both ends of the queue. Thus, "Deque" is short for "Double Ended Queue" and is pronounced "deck", like a deck of cards.
Here is a list of the topics covered in this text:
Being a
subtype all methods in the
and
interfaces are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard deque / queue implementation.
stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the
grows as needed, even if it stores its elements in an array.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Deque dequeA = new LinkedList(); Deque dequeB = new ArrayDeque();","Queue","java.util.Queue","class",0 ,"Java's
Being a
subtype all methods in the
and
interfaces are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard deque / queue implementation.
stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the
grows as needed, even if it stores its elements in an array.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Deque dequeA = new LinkedList(); Deque dequeB = new ArrayDeque();","Collection","java.util.Collection","class",0 ,"Java's
Being a
subtype all methods in the
and
interfaces are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard deque / queue implementation.
stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the
grows as needed, even if it stores its elements in an array.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Deque dequeA = new LinkedList(); Deque dequeB = new ArrayDeque();","Deque","java.util.Deque","class",1 ,"Java's
Being a
subtype all methods in the
and
interfaces are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard deque / queue implementation.
stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the
grows as needed, even if it stores its elements in an array.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Deque dequeA = new LinkedList(); Deque dequeB = new ArrayDeque();","LinkedList","java.util.LinkedList","class",0 ,"Java's
Being a
subtype all methods in the
and
interfaces are also available in the
interface.
Since
is an interface you need to instantiate a concrete implementation of the interface in order to use it. You can choose between the following
implementations in the Java Collections API:
is a pretty standard deque / queue implementation.
stores its elements internally in an array. If the number of elements exceeds the space in the array, a new array is allocated, and all elements moved over. In other words, the
grows as needed, even if it stores its elements in an array.
There are also
implementations in the java.util.concurrent
package, but I will leave the concurrency utilities out of this tutorial.
Here are a few examples of how to create a
instance:
Deque dequeA = new LinkedList(); Deque dequeB = new ArrayDeque();","ArrayDeque","java.util.ArrayDeque","class",1 ,"Java's
To add elements to the tail of a
you call its
method. You can also use the
and
methods, which add elements to the head and tail of the deque.
Deque dequeA = new LinkedList(); dequeA.add ("element 1"); //add element at tail dequeA.addFirst("element 2"); //add element at head dequeA.addLast ("element 3"); //add element at tail
The order in which the elements added to the
are stored internally, depends on the implementation. The two implementations mentioned earlier both store the elements in the order (first or last) in which they are inserted.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the
method. You can also use the
and
methods, which return the first and last element in the
. Here is how that looks:
Object firstElement = dequeA.element(); Object firstElement = dequeA.getFirst(); Object lastElement = dequeA.getLast();
Taking elements from the deque is covered later.
You can also iterate all elements of a deque, instead of just processing one at a time. Here is how that looks:
Deque dequeA = new LinkedList(); dequeA.add("element 0"); dequeA.add("element 1"); dequeA.add("element 2"); //access via Iterator Iterator iterator = dequeA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : dequeA) { String element = (String) object; }
When iterating the deque via its
or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the deque implementation.
To add elements to the tail of a
you call its
method. You can also use the
and
methods, which add elements to the head and tail of the deque.
Deque dequeA = new LinkedList(); dequeA.add ("element 1"); //add element at tail dequeA.addFirst("element 2"); //add element at head dequeA.addLast ("element 3"); //add element at tail
The order in which the elements added to the
are stored internally, depends on the implementation. The two implementations mentioned earlier both store the elements in the order (first or last) in which they are inserted.
You can peek at the element at the head of the queue without taking the element out of the queue. This is done via the
method. You can also use the
and
methods, which return the first and last element in the
. Here is how that looks:
Object firstElement = dequeA.element(); Object firstElement = dequeA.getFirst(); Object lastElement = dequeA.getLast();
Taking elements from the deque is covered later.
You can also iterate all elements of a deque, instead of just processing one at a time. Here is how that looks:
Deque dequeA = new LinkedList(); dequeA.add("element 0"); dequeA.add("element 1"); dequeA.add("element 2"); //access via Iterator Iterator iterator = dequeA.iterator(); while(iterator.hasNext(){ String element = (String) iterator.next(); } //access via new for-loop for(Object object : dequeA) { String element = (String) object; }
When iterating the deque via its
or via the for-loop (which also uses the Iterator behind the scene, the sequence in which the elements are iterated depends on the deque implementation.
To remove elements from a deque, you call the
,
and
methods. Here are a few examples:
Object firstElement = dequeA.remove(); Object firstElement = dequeA.removeFirst(); Object lastElement = dequeA.removeLast();","Deque","java.util.Deque","class",0 ,"Java's
By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Deque<MyObject> deque = new LinkedList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = deque.remove(); for(MyObject anObject : deque){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Object","java.lang.Object","class",0 ,"Java's By default you can put any
into a
, but from Java 5, Java Generics makes it possible to limit the types of object you can insert into a
. Here is an example:
Deque<MyObject> deque = new LinkedList<MyObject>();
This
can now only have MyObject
instances inserted into it. You can then access and iterate its elements without casting them. Here is how it looks:
MyObject myObject = deque.remove(); for(MyObject anObject : deque){ //do someting to anObject... }
For more information about Java Generics, see the Java Generics Tutorial.
","Deque","java.util.Deque","class",0 ,"Java's There is a lot more you can do with a
, but you will have to check out the JavaDoc for more details. This text focused on the two most common operations: Adding / removing elements, and iterating the elements.
The Collection interface (java.util.Collection) is one of the root interfaces of the Java collection classes. Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often treat these subtypes uniformly as a Collection. In this text you will see how.
Here is a list of the topics covered in this text:
Regardless of what Collection subtype you are using there are a few standard methods to add and remove elements from a Collection. Adding and removing single elements is done like this:
String anElement = "an element"; Collection collection = new HashSet(); boolean didCollectionChange = collection.add(anElement); boolean wasElementRemoved = collection.remove(anElement);
adds the given element to the collection, and returns true if the Collection changed as a result of calling the
method. A
for instance may not have changed. If the
already contained that element, it is not added again. On the other hand, if you called
on a
and the
already contained that element, the element would then exist twice in the
.
removes the given element and returns true if the removed element was present in the Collection, and was removed. If the element was not present, the
method returns false.
Regardless of what Collection subtype you are using there are a few standard methods to add and remove elements from a Collection. Adding and removing single elements is done like this:
String anElement = "an element"; Collection collection = new HashSet(); boolean didCollectionChange = collection.add(anElement); boolean wasElementRemoved = collection.remove(anElement);
adds the given element to the collection, and returns true if the Collection changed as a result of calling the
method. A
for instance may not have changed. If the
already contained that element, it is not added again. On the other hand, if you called
on a
and the
already contained that element, the element would then exist twice in the
.
removes the given element and returns true if the removed element was present in the Collection, and was removed. If the element was not present, the
method returns false.
Regardless of what Collection subtype you are using there are a few standard methods to add and remove elements from a Collection. Adding and removing single elements is done like this:
String anElement = "an element"; Collection collection = new HashSet(); boolean didCollectionChange = collection.add(anElement); boolean wasElementRemoved = collection.remove(anElement);
adds the given element to the collection, and returns true if the Collection changed as a result of calling the
method. A
for instance may not have changed. If the
already contained that element, it is not added again. On the other hand, if you called
on a
and the
already contained that element, the element would then exist twice in the
.
removes the given element and returns true if the removed element was present in the Collection, and was removed. If the element was not present, the
method returns false.
You can also add and remove collections of objects. Here are a few examples:
Set aSet = ... // get Set with elements from somewhere List aList = ... // get List with elements from somewhere Collection collection = new HashSet(); collection.addAll(aSet); //returns boolean too, but ignored here. collection.addAll(aList); //returns boolean too, but ignored here. collection.removeAll(aList); //returns boolean too... collection.retainAll(aSet); //returns boolean too...
adds all elements found in the Collection passed as parameter to the method. The Collection object itself is not added. Only its elements. If you had called
with the Collection as parameter instead, the Collection object itself would have been added, not its elements.
Exactly how thet
method behaves depends on the Collection subtype. Some Collection subtypes allows the same element to be added more than once, and others don't.
removes all elements found the Collection passed as parameter to the method. If the Collection parameter contains any elements not found the target collection, these are just ignored.
does the opposite of
. Instead of removing all the elements found in the parameter Collection, it keeps all these elements, and removes all other elements. Keep in mind, that only if the elements were already contained in the target collection, are they retained. Any new elements found in the parameter Collection which are not in the target collection, are not automatically added. They are just ignored.
The Collection interface has two methods to check if a Collection contains one or more certain elements. These are the
and
methods. They are illustrated here:
Collection collection = new HashSet(); boolean containsElement = collection.contains("an element"); Collection elements = new HashSet(); boolean containsAll = collection.containsAll(elements);
returns true if the collection contains the element, and false if not.
returns true if the collection contains all the elements in the parameter collection, and false if not.
You can check the size of a collection using the
method. By "size" is meant the number of elements in the collection. Here is an example:
int numberOfElements = collection.size();","Collection","java.util.Collection","class",0 ,"Java's
You can iterate all elements of a collection. This is done by obtaining an
from the collection, and iterate through that. Here is how it looks:
Collection collection = new HashSet(); //... add elements to the collection Iterator iterator = collection.iterator(); while(iterator.hasNext()){ Object object = iterator.next(); //do something to object; }
You can also use the new for-loop:
Collection collection = new HashSet(); //... add elements to the collection for(Object object : collection) { //do something to object; }","Iterator","java.util.Iterator","class",0 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","SortedMap","java.util.SortedMap","class",1 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","Map","java.util.Map","class",0 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","Comparable","java.lang.Comparable","class",0 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","Comparator","java.util.Comparator","class",0 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","SortedSet","java.util.SortedSet","class",0 ,"Java's
The
interface is a subtype of the
interface, with the addition that the elements stored in the map are sorted internally.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedMap mapA = new TreeMap(); Comparator comparator = new MyComparator(); SortedMap mapB = new TreeMap(comparator);","TreeMap","java.util.TreeMap","class",0 ,"Java's
There is actually a lot more you can do with a
that is not part of the
interface, like getting a descending key set etc. Check out the JavaDoc's for more detail about these features.
There is actually a lot more you can do with a
that is not part of the
interface, like getting a descending key set etc. Check out the JavaDoc's for more detail about these features.
The
interface is a subtype of the
interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a
the elements are returned in the sorted order.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedSet setA = new TreeSet(); Comparator comparator = new MyComparator(); SortedSet setB = new TreeSet(comparator);","SortedSet","java.util.SortedSet","class",1 ,"Java's
The
interface is a subtype of the
interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a
the elements are returned in the sorted order.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedSet setA = new TreeSet(); Comparator comparator = new MyComparator(); SortedSet setB = new TreeSet(comparator);","Set","java.util.Set","class",0 ,"Java's
The
interface is a subtype of the
interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a
the elements are returned in the sorted order.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedSet setA = new TreeSet(); Comparator comparator = new MyComparator(); SortedSet setB = new TreeSet(comparator);","Comparable","java.lang.Comparable","class",0 ,"Java's
The
interface is a subtype of the
interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a
the elements are returned in the sorted order.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedSet setA = new TreeSet(); Comparator comparator = new MyComparator(); SortedSet setB = new TreeSet(comparator);","Comparator","java.util.Comparator","class",0 ,"Java's
The
interface is a subtype of the
interface. It behaves like a normal set with the exception that the elements are sorted internally. This means that when you iterate the elements of a
the elements are returned in the sorted order.
The order of the sorting is either the natural sorting order of the elements (if they implement
), or the order determined by a
that you can give to the
.
By default the elements are iterated in ascending order, starting with the "smallest" and moving towards the "largest". But it is also possible to iterate the elements in descending order using the method
.
The Java Collections API only has one implementation of the
interface - the
class. The java.util.concurrent
package also has an implementation of this interface, but I will leave the concurrency utilities out of this trail.
Here are two examples of how to create a
:
SortedSet setA = new TreeSet(); Comparator comparator = new MyComparator(); SortedSet setB = new TreeSet(comparator);","TreeSet","java.util.TreeSet","class",1 ,"Java's
There is actually a lot more you can do with a
that is not part of the
interface, like getting the highest and lowest element, splitting the set into subsets based on two values etc. Check out the JavaDoc if you need any of these more special features.
There is actually a lot more you can do with a
that is not part of the
interface, like getting the highest and lowest element, splitting the set into subsets based on two values etc. Check out the JavaDoc if you need any of these more special features.
The
interface is a subtype of the
interface. It behaves like a
with the exception you have navigation methods available in addition to the sorting mechanisms of the
. In this text I will look closer at some of these navigation methods.
In Java 6 there is only one implementation of the
interface in the java.util
package:
There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It behaves like a
with the exception you have navigation methods available in addition to the sorting mechanisms of the
. In this text I will look closer at some of these navigation methods.
In Java 6 there is only one implementation of the
interface in the java.util
package:
There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The
interface is a subtype of the
interface. It behaves like a
with the exception you have navigation methods available in addition to the sorting mechanisms of the
. In this text I will look closer at some of these navigation methods.
In Java 6 there is only one implementation of the
interface in the java.util
package:
There is an implementation in the java.util.concurrent
package but that is outside the scope of this trail.
Here is a list of the topics covered in this text:
The first interesting navigation methods are the
and
methods.
The
method returns a
in which the order of the elements is reversed compared to this one. The returned "view" is backed by the original
, so changes to the descending set are also reflected in the original set.
Here is a simple example:
NavigableSet reverse = original.descendingSet();
The
method allows you to iterate the elements of the
(which is also a
) in reverse order, without changing the order of the elements internally.
Iterator reverse = original.descendingIterator();","NavigableSet","java.util.NavigableSet","class",1 ,"Java's
The first interesting navigation methods are the
and
methods.
The
method returns a
in which the order of the elements is reversed compared to this one. The returned "view" is backed by the original
, so changes to the descending set are also reflected in the original set.
Here is a simple example:
NavigableSet reverse = original.descendingSet();
The
method allows you to iterate the elements of the
(which is also a
) in reverse order, without changing the order of the elements internally.
Iterator reverse = original.descendingIterator();","SortedSet","java.util.SortedSet","class",0 ,"Java's
The
method returns a view of the original
which only contains elements that are "less than" the given element. Here is an example:
NavigableSet original = new TreeSet(); original.add("1"); original.add("2"); original.add("3"); //this headset will contain "1" and "2" SortedSet headset = original.headSet("3"); //this headset will contain "1", "2", and "3" because "inclusive"=true NavigableSet headset = original.headSet("3", true);
The
method works the same way, except it returns all elements that are higher than the given parameter element.
The
allows you to pass two parameters demarcating the boundaries of the view set to return. The elements matching the first boundary is included, where as elements matching the last boundary are not. Here is an example:
NavigableSet original = new TreeSet(); original.add("1"); original.add("2"); original.add("3"); original.add("4"); original.add("5"); //this subset will contain "2" and "3" SortedSet subset = original.subSet("2", "4"); //this subset will contain "2", "3" and "4" because // fromInclusive=true, and toInclusive=true NavigableSet subset = original.subSet("2", true, "4", true);","NavigableSet","java.util.NavigableSet","class",1 ,"Java's
The
method returns the least (smallest) element in this set that is greater than or equal to the element passed as parameter to the
method. Here is an example:
NavigableSet original = new TreeSet(); original.add("1"); original.add("2"); original.add("3"); //ceiling will be "2". Object ceiling = original.ceiling("2"); //floor will be "2". Object floor = original.floor("2");
The
method does the opposite of
The
method returns the least (smallest) element in this set that is greater than (not equal too) the element passed as parameter to the
method. Here is an example:
NavigableSet original = new TreeSet(); original.add("1"); original.add("2"); original.add("3"); //higher will be "3". Object higher = original.higher("2"); //lower will be "1" Object lower = original.lower("2");
The
method does the opposite of the
method.
The
method returns and removes the "first" element in the
or null if the set is empty. The
returns and removes the "last" element in the set or null if the set is empty. "First" means smallest element according to the sort order of the set. "Last" means largest according to teh element sorting order of the set.
Here are two examples:
NavigableSet original = new TreeSet(); original.add("1"); original.add("2"); original.add("3"); //first is "1" Object first = original.pollFirst(); //last is "3" Object last = original.pollLast();","NavigableSet","java.util.NavigableSet","class",1 ,"Generic
It is possible to generify the various Collection and Map types and subtypes in the Java collection API. This text will not cover generics in detail. Java Generics is covered in my Java Generics tutorial.
The Collection interface can be generified like this:
Collection<String> stringCollection = new HashSet<String>();
This stringCollection
can now only contain
instances. If you try to add anything else, or cast the elements in the collection to any other type than
, the compiler will complain.
Actually, it is possible to insert other objects than String objects, if you cheat a little (or is just plain stupid), but this is not recommended.
You can iterate the above collection using the new for-loop, like this:
Collection<String> stringCollection = new HashSet<String>(); for(String stringElement : stringCollection) { //do something with each stringElement }
You can do the same thing with
,
etc.
I won't get into much more detail about generic collections here. Like I said in the beginning, I have a separate Java Generics tutorial. Additionally, more generic examples will be shown in the texts on the specific collection types.
","Collections","java.util.Collections","class",0 ,"GenericIt is possible to generify the various Collection and Map types and subtypes in the Java collection API. This text will not cover generics in detail. Java Generics is covered in my Java Generics tutorial.
The Collection interface can be generified like this:
Collection<String> stringCollection = new HashSet<String>();
This stringCollection
can now only contain
instances. If you try to add anything else, or cast the elements in the collection to any other type than
, the compiler will complain.
Actually, it is possible to insert other objects than String objects, if you cheat a little (or is just plain stupid), but this is not recommended.
You can iterate the above collection using the new for-loop, like this:
Collection<String> stringCollection = new HashSet<String>(); for(String stringElement : stringCollection) { //do something with each stringElement }
You can do the same thing with
,
etc.
I won't get into much more detail about generic collections here. Like I said in the beginning, I have a separate Java Generics tutorial. Additionally, more generic examples will be shown in the texts on the specific collection types.
","String","java.lang.String","class",0 ,"GenericIt is possible to generify the various Collection and Map types and subtypes in the Java collection API. This text will not cover generics in detail. Java Generics is covered in my Java Generics tutorial.
The Collection interface can be generified like this:
Collection<String> stringCollection = new HashSet<String>();
This stringCollection
can now only contain
instances. If you try to add anything else, or cast the elements in the collection to any other type than
, the compiler will complain.
Actually, it is possible to insert other objects than String objects, if you cheat a little (or is just plain stupid), but this is not recommended.
You can iterate the above collection using the new for-loop, like this:
Collection<String> stringCollection = new HashSet<String>(); for(String stringElement : stringCollection) { //do something with each stringElement }
You can do the same thing with
,
etc.
I won't get into much more detail about generic collections here. Like I said in the beginning, I have a separate Java Generics tutorial. Additionally, more generic examples will be shown in the texts on the specific collection types.
","List","java.util.List","class",0 ,"GenericIt is possible to generify the various Collection and Map types and subtypes in the Java collection API. This text will not cover generics in detail. Java Generics is covered in my Java Generics tutorial.
The Collection interface can be generified like this:
Collection<String> stringCollection = new HashSet<String>();
This stringCollection
can now only contain
instances. If you try to add anything else, or cast the elements in the collection to any other type than
, the compiler will complain.
Actually, it is possible to insert other objects than String objects, if you cheat a little (or is just plain stupid), but this is not recommended.
You can iterate the above collection using the new for-loop, like this:
Collection<String> stringCollection = new HashSet<String>(); for(String stringElement : stringCollection) { //do something with each stringElement }
You can do the same thing with
,
etc.
I won't get into much more detail about generic collections here. Like I said in the beginning, I have a separate Java Generics tutorial. Additionally, more generic examples will be shown in the texts on the specific collection types.
","Set","java.util.Set","class",0