Showing posts with label Interface. Show all posts
Showing posts with label Interface. Show all posts

Wednesday, April 10, 2013

TreeMap


  • The TreeMap is part of the Java Collections Framework.
  • TreeMap is a concrete class which implements the Map interface, which maps keys to values. 
  • Keys are like the index of an ArrayList except that the index of an ArrayList is an int. A map key can be any object.
  • A map cannot contain duplicate keys - each key maps to one value.
  • A key and it's corresponding value form an entry or entry-set. Let's call them key/value pairs.
  • A TreeMap is sorted by the natural ordering of it's keys.


Instantiation
Map<key,Value> = new TreeMap<Key,Value>();

(As map is an Interface, it cannot be instantiated.)

get(Object key)
Returns the value for the specified key. If a value at that key does not exist, null is returned. While this is most forgiving, always check the return value for null before attempting to use it.

Object o = myMap.get(x);
if (o != null) {...};


containsKey(int key)
Returns True if the specified key is found in the map. (False is not!).

if (myMap.containsKey(x)) {...};


put(Object key, Object value)
Puts the new value at the specified key. If the key already exists, the old value is replaced. So be careful!

myMap.put(x,o);

size()
Returns the number of key/value pairs.

myMap.size();

remove(int key)
Removes the value at the specified key. If no value as associated with the key, the method simply exits.

myMap.remove(x);

putAll(Map)
Copies all of the mappings from the specified map, to this map. Both maps must have the same key and value type. Beware though, if there are values for identical keys, the old value will be replaced with the new value - as per the *no duplicates* rule.
For instance:

Map<Integer, String> mapOne = new TreeMap<Integer,String>();
mapOne.put(10, "ten");
mapOne.put(3, "three");

Map<Integer,String> mapTwo = new TreeMap<Integer,String>();
mapTwo.put(50, "fifty");
mapTwo.put(10, "ten");

mapOne.putAll(mapTwo);

mapOne now contains the following key/value pairs (sorted):

  • 3, "three"
  • 10, "ten"
  • 50, "fifty"


Iterating (looping) using Enhanced For Loop

The following methods are utilised in the enhanced for loop example below:

  • entrySet() returns a view of the key/value pairs in the map.
  • getKey() returns the key in the current iteration.
  • getValue() returns the value of the key in the current iteration

In plain English, we are saying that for each Integer and String, key/value pair in the map.


for (Map.Entry<Integer, String> mapEntries : mapOne.entrySet()) {
      int key = mapEntries.getKey();
      String value = mapEntries.getValue();
      System.out.println("Key is: " + key);
      System.out.println("Value is: " + value);
}

We would expect the output to look like:

3
three
10
ten
50
fifty

Pulling keys or values out of Map and into ArrayList

In this example, a map of Integer,Integer is split into two lists - one for keys and one for values.

List<Integer> listOfMapKeys = new ArrayList<Integer>(mapname.keySet());
List<Integer> listOfMapValues = new ArrayList<Integer>(mapname.values());


But the coolest stuff is yet to come!!! Read on in NavigableMap Interface >>>

(also, will post code download soon too!)

(also, IS ANYONE READING THIS?) :p








NavigableMap Interface

......

Tuesday, January 8, 2013

What is an Interface?

DOWNLOAD THE CODE: InterfaceExample

An interface specifies the behaviours that should be present within all classes that implement (use) it. An interface contains method signatures only. There is no method implementation - there is no method body. See class diagram below:



Each behaviour defined in the interface must be implemented (coded) in any classes that implement (use) it.

The implements keyword is used to implement an interface in a class. The figure below shows the class declaration for the Person class which has been modified to implement the class called IPerson.





Interface naming convention
The naming convention for an interface is a capital I followed by a meaningful name. As the interface in this example was only designed to be used with the Person class, I have called it IPerson.

Why use an interface?
Interfaces provide a standard and consistency for communication between classes and other parts of a system.

Consider the teacher who gives her students the outline for the functional requirements of a system. Each student produces a design and implementation but has perhaps forgotten to include methods, method parameters or simply used different spelling for method names. The student adds the teachers test harness to the code but is immediately faced with compilation errors due to misspelling & missing detail.

For the next project however, as well as giving the students the functional requirements of a system, the teacher also gives them a number of interfaces to develop to, ensuring that all methods, method parameters & spelling, as used by the test harness, will be implemented in the students code.

Multiple interfaces
A class may implement many interfaces.




In the diagram above, the Weapon class implements both the IStats and IBattle interface. This means that the Weapon class must implement the methods which are present in both interfaces.

The Weapon class can now be used in the context of IStats and IBattle type.


Interface as type
Where a class implements an interface, objects of that class may be treated as objects of the interface type.

For instance:

ArrayList<IBattle> battleObjectList = new ArrayList<IBattle>();
battleList.add(new weapon);
battleList(new Arena());

All objects in the list have the context of IBattle and only the methods specified in the IBattle  interface are accessible.


Java Interfaces
As well as the interface types you will write yourself, there are numerous predefined interface types in the Java API such as MouseListener, List, Map.

See also:
"What Is an Interface? (The Java™ Tutorials > Learning the Java Language > Object-Oriented Programming Concepts)" ( http://bit.ly/Rph8eP )