(→Class Album) |
(→Execution) |
||
Line 163: | Line 163: | ||
* java -cp /usr/share/java/junit.jar:. junit.textui.TestRunner AlbumTest | * java -cp /usr/share/java/junit.jar:. junit.textui.TestRunner AlbumTest | ||
+ | |||
+ | Output: | ||
+ | |||
+ | .. | ||
+ | Time: 0.004 | ||
+ | |||
+ | OK (2 tests) | ||
[[category:OOP]] | [[category:OOP]] |
Considere uma caderneta de cromos. Os cromos têm um número e uma imagem. Não é necessário modelar a imagem, considere a imagem como sendo uma instância da seguinte classe:
<java5> class Image { /* conteúdo omitido */ } </java5>
A caderneta guarda os cromos pela ordem de numeração e não permite guardar cromos repetidos. É possível adicionar cromos a uma caderneta (método add) e é possível remover um cromo se for indicado o seu número (método remove). Duas cadernetas dizem-se iguais (equals) se tiverem o mesmo número de cromos (independentemente das características dos cromos individuais). É possível obter uma lista ordenada (por número) contendo os cromos de uma caderneta (método getAll).
This is a very simple and uninteresting class.
<java5> public class Image {
} </java5>
<java5> /**
* The card class. */
public class Card implements Comparable<Card> {
/** * The card number. */ private int _id;
/** * The image in this card. */ private Image _image;
/** * How to initialise a new card. * * @param id * @param image */ public Card(int id, Image image) { _id = id; _image = image; }
/** * @return the card number. */ public int getId() { return _id; }
/** * @return image in this card. */ public Image getImage() { return _image; }
/** * @see java.lang.Comparable#compareTo(java.lang.Object) */ @Override public int compareTo(Card other) { return _id - other.getId(); }
} </java5>
<java5> import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.TreeMap;
/**
* An album is built around a tree map, so that card order can be used. */
public class Album {
/** * The card collection. */ private TreeMap<Integer, Card> _cards = new TreeMap<Integer, Card>();
/** * @return sorted list (comparable cards). */ public List<Card> getAll() { List<Card> lst = new LinkedList<Card>(); lst.addAll(_cards.values()); Collections.sort(lst); return lst; }
/** * Store a card. If a card has a number already in the tree, it replaces the * old one (alternatively, we could refuse storing a card with an existing * number). * * @param card */ public void add(Card card) { _cards.put(card.getId(), card); }
/** * Remove a card. * * @param id * card number */ public void remove(int id) { _cards.remove(id); }
/** * @return number of cards. */ public int size() { return _cards.size(); }
/** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object other) { if (other instanceof Album) { Album album = (Album)other; return size() == album.size(); } return false; } } </java5>
Output:
.. Time: 0.004 OK (2 tests)