Docsity

Standard Template Library and the Java Collections Classes, Slides of Java Programming

Toggle sidebar
bg1
Standard Template Library and the Java Collections Classes
Both C++ and Java have libraries that let us implement common data structures. C++ has STL, the
Standard Template Library, and Java has the Collections classes. For high-level applications it is relatively
rare to build your own linked list, hash table, binary search tree, etc. Instead these are already
implemented for us through these classes! Nevertheless the occasion does arise to construct your own
class or to modify the class, so it is important to know how the lower-level algorithms work.
The easiest way to demonstrate the classes is through code, so let’s go straight to some examples!
C++ Standard Template Library
Documentation for the library is here: https://www.sgi.com/tech/stl/table_of_contents.html
Here we will just give a few examples for a couple of the classes in this library. You’ve already been using
one of the classes in this library, the string class, which abstracts away the messiness of C-style strings
terminated by a null character. As the name implies, the library uses templates. This allows you to
substitute the data type of your choice into the class.
Vector
The vector class is like a cross between an array and a linked list. You can add items dynamically to the
vector and access it like an array. Here is an example:
#include <iostream>
#include <vector>
using namespace std;
int main( )
{
vector<int> v;
cout << "Enter a list of positive numbers.\n"
<< "Place a negative number at the end.\n";
int next;
cin >> next;
while (next > 0)
{
v.push_back(next);
cout << next << " added. ";
cout << "v.size( ) = " << v.size( ) << endl;
cin >> next;
}
cout << "You entered:\n";
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff

Partial preview of the text

Download Standard Template Library and the Java Collections Classes and more Slides Java Programming in PDF only on Docsity!

Standard Template Library and the Java Collections Classes

Both C++ and Java have libraries that let us implement common data structures. C++ has STL, the

Standard Template Library, and Java has the Collections classes. For high-level applications it is relatively

rare to build your own linked list, hash table, binary search tree, etc. Instead these are already

implemented for us through these classes! Nevertheless the occasion does arise to construct your own

class or to modify the class, so it is important to know how the lower-level algorithms work.

The easiest way to demonstrate the classes is through code, so let’s go straight to some examples!

C++ Standard Template Library

Documentation for the library is here: https://www.sgi.com/tech/stl/table_of_contents.html

Here we will just give a few examples for a couple of the classes in this library. You’ve already been using

one of the classes in this library, the string class, which abstracts away the messiness of C-style strings

terminated by a null character. As the name implies, the library uses templates. This allows you to

substitute the data type of your choice into the class.

Vector

The vector class is like a cross between an array and a linked list. You can add items dynamically to the

vector and access it like an array. Here is an example:

#include

#include

using namespace std;

int main( )

vector v;

cout << "Enter a list of positive numbers.\n"

<< "Place a negative number at the end.\n";

int next;

cin >> next;

while (next > 0)

v.push_back(next);

cout << next << " added. ";

cout << "v.size( ) = " << v.size( ) << endl;

cin >> next;

cout << "You entered:\n";

for (unsigned int i = 0; i < v.size( ); i++)

cout << v[i] << " ";

cout << endl;

return 0;

We can use an iterator to access items in the STL collection. An iterator lets us move back and forth

between items in the collection.

//Program to demonstrate STL iterators.

#include

#include

using std::cout;

using std::endl;

using std::vector;

using std::vector::iterator;

int main( )

vector container;

for (int i = 1; i <= 4; i++)

container.push_back(i);

cout << "Here is what is in the container:\n";

iterator p;

for (p = container.begin( ); p != container.end( ); p++)

cout << *p << " ";

cout << endl;

cout << "Setting entries to 0:\n";

for (p = container.begin( ); p != container.end( ); p++)

*p = 0;

cout << "Container now contains:\n";

for (p = container.begin( ); p != container.end( ); p++)

cout << *p << " ";

cout << endl;

return 0;

The new C++11 ranged-based for loop and the “auto” type makes it easy to loop through vectors. This

version outputs the numbers in the vector.

vector vec;

vec.push_back( 10 );

Stack

The stack class behaves just like the stack data structure we discussed previously. Here is an example:

//Program to demonstrate use of the stack template class from the STL.

#include

#include

using std::cin;

using std::cout;

using std::endl;

using std::stack;

int main( )

stack s;

cout << "Enter a line of text:\n";

char next;

cin.get(next);

while (next != '\n')

s.push(next);

cin.get(next);

cout << "Written backward that is:\n";

while (! s.empty( ) )

cout << s.top( );

s.pop( );

cout << endl;

return 0;

The key functions are push, pop, top, and empty.

Set

The set template class is, in some sense, the simplest container you can imagine. It stores elements

without repetition. The first insertion places an element in the set. Additional insertions after the first

have no effect, so that no element appears more than once. Each element is its own key. Basically, you

just add or delete elements and ask if an element is in the set or not. Like all STL classes, the set

template class was written with efficiency as a goal. To work efficiently, a set object stores its values in

sorted order.

//Program to demonstrate use of the set template class.

#include

#include

using std::cout;

using std::endl;

using std::set;

int main( )

set s; s.insert('A'); s.insert('D'); s.insert('D'); s.insert('C'); s.insert('C'); s.insert('B'); cout << "The set contains:\n"; for (auto element : s) cout << element << endl; cout << endl; cout << "Set contains 'C': "; if (s.find('C') == s.end()) cout << " no " << endl; else cout << " yes " << endl; cout << "Removing C.\n"; s.erase('C'); for (auto element : s) cout << element << endl; cout << endl; cout << "Set contains 'C': "; if (s.find('C') == s.end()) cout << " no " << endl; else cout << " yes " << endl;

return 0;

Java Collections

Java has a collections framework that is similar to the Standard Template Library, but does make

inheritance and polymorphism a larger component of the library. There are several classes in the library;

here is an overview:

There are some methods that every class implements in the Collections framework. This is kind of nice

because you can get used to using methods like size() or toArray() or contains() and apply them to any

collection.

public boolean isEmpty() True if the calling object is empty

public boolean contains(Object target) True if the calling object contains target

public int size() Number of elements in the calling object

public boolean equals(Object other) Our standard equality method

public Object[] toArray() Return items in the collection as an array

ArrayList

Let’s start with the ArrayList. Java has a vector class like C++, but in most cases we will use the ArrayList

instead. It is pretty straightforward to use:

To access the arraylist code we can import the class via:

import java.util.ArrayList;

To create a variable of type ArrayList that is a list of type DataType use the following:

ArrayList varName = new ArrayList();

If you know how many items the arraylist will likely need, execution can be a bit faster by specifying an

initial capacity.

Here is a basic example:

import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList stringList = new ArrayList(); stringList.add("foo"); stringList.add("bar"); stringList.add("zot"); stringList.add("bah"); System.out.println("Size of List: " + stringList.size()); System.out.println("Contents:"); for (int i = 0; i < stringList.size(); i++) { System.out.println("At index " + i + " value=" + stringList.get(i)); } stringList.remove("bar"); System.out.println("Contents after remove bar:"); for (int i = 0; i < stringList.size(); i++) { System.out.println("At index " + i + " value=" + stringList.get(i)); } stringList.remove(1); System.out.println("Contents after remove 1:"); for (int i = 0; i < stringList.size(); i++) { System.out.println("At index " + i + " value=" + stringList.get(i)); }

int i; // First add 4 numbers to the arraylist for (i=0; i<4; i++) { v.add(new MyIntClass(i)); } // Print out size of the arraylist, should be 4 System.out.println("Size: " + v.size() + "\n"); // Print arraylist System.out.println("Original arraylist:"); PrintArraylist(v); // Remove the second element v.remove(2); // Print out the elements again System.out.println("After remove:"); PrintArraylist(v); // Insert the number 100 at position 1 v.add(1, new MyIntClass(100)); // Print out the elements again System.out.println("After insert:"); PrintArraylist(v); } // This method prints out the elements in the arraylist public static void PrintArraylist(ArrayList v) { MyIntClass temp; int i; for (i=0; i<v.size(); i++) { temp = v.get(i); System.out.println(temp.m_value); } System.out.println(); } }

Let’s try using the indexOf method:

// Index of - System.out.println("Position of 1"); System.out.println(v.indexOf(new MyIntClass(1)));

Adding this gives an output of:

Position of 1

This is not right, the list has a node with the value of 1 in position 2. We are getting -1 back because the

indexOf method invokes the equals method for the BaseType object to determine which item in the

arraylist matches the target. However, we didn’t define one ourselves, so our program is really using

the equals method defined for Object (which is inherited automatically for any object we make).

However, this definition of equals only checks to see if the addresses of the objects are identical, which

they are not in this case. What we really need to do is see if the integer values are the same by defining

our own equals method. Add to the MyIntClass object:

public boolean equals(Object otherIntObject) { MyIntClass otherInt = (MyIntClass) otherIntObject; if (this.m_value == otherInt.m_value) return true; return false; }

If we run the program now, it will output:

Position of 1 2

A few comments of note: First, we had to define equals with an input parameter of type Object.

This is because this is how the method is defined in the Object class which we need to override (and is

invoked by the indexOf method). This means we have to typecast the object back to our class of

MyIntClass. Once this is done we can compare the ints.

For Each Loop

Iterating through an arraylist is such a common occurrence that Java includes a special type of loop

specifically for this purpose. Called the for-each loop, it allows you to easily iterate through every item

in the arraylist. The syntax looks like this:

for (BaseType varName : ArrayListVariable)

Statement with varName

Here is a modified version of the PrintArrayList method from the previous example, but using the for

each loop:

// This method prints out the elements in the arraylist public static void PrintArraylist(ArrayList v) { for (MyIntClass intObj : v) { System.out.println(intObj.m_value); } System.out.println(); }

(green.contains("peas")))));

System.out.println("pie and grass in same set? " +

((round.contains("pie") &&

(round.contains("grass"))) ||

(green.contains("pie") &&

(green.contains("grass")))));

// To union two sets we use the addAll method.

HashSet setUnion = new HashSet(round);

round.addAll(green);

System.out.println("\nUnion of green and round:");

outputSet(setUnion);

// To intersect two sets we use the removeAll method.

HashSet setInter = new HashSet(round);

setInter.removeAll(green);

System.out.println("\nIntersection of green and round:");

outputSet(setInter);

System.out.println();

It is important to note that if you intend to use the HashSet class with your own class as the

parameterized type T, then your class must override the following methods:

public int hashCode();

public boolean equals(Object obj);

Why? hashCode is needed for the hash function to work well. The equals method is used to determine

if two objects in the set are the same.

Map and HashMap

The map framework works the same way as a map in C++ STL. It lets you map one type onto another.

There are several implementations of a map, including a TreeMap or LinkedHashMap or a HashMap. If

you use a HashMap, you must make sure the item being mapped overrides the hashCode() and equals()

methods as described above for HashSet.

import java.util.HashMap;

import java.util.Scanner;

public class HashMapDemo

public static void main(String[] args)

// First create a hashmap with an initial size of 10 and

// the default load factor

HashMap<Integer,String> employees = new HashMap<Integer,String>(10);

// Add several employees objects to the map using

// their id as the key

employees.put(10, "Joe");

employees.put(49, "Andy");