0% found this document useful (0 votes)
18 views5 pages

Examen de rattrapage NFA035 Java

Java exercises and solution
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Examen de rattrapage NFA035 Java

Java exercises and solution
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ISSAE – CNAM Liban NFA035: Examen de rattrapage 2019-2020

UE : Programmation Java – Bibliothèques et Patterns : NFA035


Centres : Beyrouth, Baalbek, Tripoli, Bikfaya, Nahr Ibrahim
Examen : Rattrapage
Modalité : Devoir noté (copies écrites à la main)
Date : 22.10.2020
Heures : 18:00h
Durée : 60 minutes

1
ISSAE – CNAM Liban NFA035: Examen de rattrapage 2019-2020

FRANCAIS
EXERCICE 1: Collections et Généricité
Nous voudrions implémenter une HashMap générique (HashMap<k,v>) en utilisant des structures de
données linéaires comme les tableaux et les listes.
Notre HashMap sera formée de deux listes :
La première liste à éléments uniques sera utilisée pour stocker les clés.
La deuxième liste sera utilisée pour stocker les valeurs.
Les deux listes seront implémentées par tableaux.
La liaison entre clé et valeur sera implémentée à travers les indices égaux dans les deux listes.
Une liste implémentée par tableau montrerait comme suit :

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

last 12

Les fonctionnalités principales d’une liste sont les suivantes :


size() : la taille de la liste.
isEmpty() : vérifie si la liste est vide.
contains(…) : vérifie si la liste contient un élément spécifique donné en paramètre.
get(…) : renvoie l’élément qui existe à l’indice donné en paramètre.
add(…) : ajoute à la liste l’élément donné en paramètre
indexOf(…) : renvoie l’indice de l’élément donné en paramètre
realloc() : permet de faire une réallocation dynamique du tableau, c.à.d. étendre la longueur
du tableau d’une valeur constante.

Vous devriez spécifier les paramètres de ces méthodes et le type de retour.

Question 1.
Implémenter les deux listes demandées.
Vous devriez établir un modèle qui ressemble au Java Collection Framework c.à.d. utiliser des
interfaces et des classes abstraites pour grouper les méthodes de la structure à implémenter.

Question 2.

Implementez la HashMap en y incluant les fonctionnalites principales, c.a.d. les methodes


put et get.

2
ISSAE – CNAM Liban NFA035: Examen de rattrapage 2019-2020

ENGLISH

EXERCISE 1: Collections et Generics


We would like to implement a generic HashMap (HashMap<k,v>) using linear data structures such
as arrays and lists.
Our HashMap will be formed of two lists:
The first list with unique elements will be used to store the keys.
The second list will be used to store values (accepts duplicates).
Both lists will be implemented by array.
The link between key and value will be implemented through equal indexes in the two lists.

A list implemented by array looks as follows :

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

last 12

The main fuctionalities of lists are the followings :


size() : number of elements.
isEmpty() : checks if a list contains elements.
contains(…) : checks if a list contains a specific element given in parameter.
get(…) : returns the element that exists a the index given in parameter.
add(…) : adds to the list the element given in parameter.
indexOf(…) : returns the index of the elements given in parameter
realloc() : allows making a dynamic reallocation of the array, i.e. extends the capacity of the
list of a constant value.

You must specify the parameters of these methods and their return type.

Question 1.

Implement these two types of lists.


You must establish a model that is similar to the Java Collection Framework i.e. using interfaces and
abstract classes in order to group the methods of the requested data structure.

Question 2.

Implement the HashMap including its main functionalities, i.e. the methods put and get.

3
ISSAE – CNAM Liban NFA035: Examen de rattrapage 2019-2020

Question 1.

Solution
public interface MList<E> { (2 pts)
final int extension = 10;
public int size();
public boolean isEmpty();
public boolean contains(Object e);
public E get(int i);
public boolean add(E e);
public int indexOf(E e);
public void realloc();
}
public abstract class AbsList<E> implements MList<E> { (7 pts)
E[] elem;
int last;
public AbsList(int n){
elem = (E[]) new Object[n];
last = -1;}

public int size() { return last+1; }


public boolean isEmpty() { return last == -1; }
public boolean contains(Object e){
if(!isEmpty())
for(int i=0; i<[Link]; i++)
if([Link](elem[i])) return true;
return false; }

public E get(int p){


if(p>=0 && p<=last) return elem[p];
return null;}

public int indexOf(E e){


if(contains(e))
for(int i=0; i<=last; i++)
if([Link](elem[i])) return i;
return -1;}

public void realloc() {


elem = [Link](elem, [Link]+extension);}
}

public class UniqueList<E> extends AbsList<E> { (3 pts)


public UniqueList(int n) { super(n); }
public boolean add(E e){
if(!contains(e)){
if(last == [Link]-1) realloc();
elem[++last] = e;
return true; }
return false;}
}

public class RegularList<E> extends AbsList<E> { (3 pts)

4
ISSAE – CNAM Liban NFA035: Examen de rattrapage 2019-2020

public RegularList(int n) { super(n); }


public boolean add(E e) {
if(last == [Link]-1) realloc();
elem[++last] = e;
return true;}
}

Question 2.
Solution
public class HashMap<K,V> { (5 pts)
UniqueList<K> keys;
RegularList<V> values;

public HashMap(int initialCapacity) {


keys = new UniqueList<K>(initialCapacity);
values = new RegularList<V>(initialCapacity);}

public boolean put(K key, V value){


if([Link](key)){
[Link](value);
return true; }
return false; }
public V get(K key){
return [Link](key) ? [Link]([Link](key)) : null;}
}

Common questions

Powered by AI

The HashMap implementation employs dynamic reallocation as a strategy to handle potential capacity limitations of arrays. The realloc method is used when adding an element would exceed the current capacity of the array. This method extends the array's capacity by a predefined constant value, which allows the list to grow dynamically as more elements are added. Additionally, the check for available space (via the condition if(last == elem.length-1)) is integral to deciding when to perform a reallocation to prevent array overflow .

In this context, Java interfaces and abstract classes are utilized to create models similar to the Java Collection Framework by defining a set of methods in the MList interface that dictate the expected behavior of the lists, such as size, isEmpty, contains, and others. The abstract class AbsList provides a partial implementation of these methods, allowing common functionality to be shared while still being able to override or expand upon in concrete subclasses like UniqueList and RegularList. This approach promotes code reuse, modularity, and the separation of interface and implementation, aligning with the design principles of the Java Collection Framework .

Advantages include simplicity and direct access through array indices, which can make certain operations like get and indexOf relatively fast compared to more complex structures. Arrays also have a lower memory overhead compared to linked structures. However, disadvantages include poor performance in dynamic size adjustments, as reallocations are costly in terms of time complexity. Arrays have limited capacity that needs to be managed manually, requiring reallocation logic to handle increases, which can slow down applications significantly when large re-sizes occur frequently .

Using arrays to implement functionalities like add and realloc in a generic HashMap has several implications. For add, the process involves checking if the array is full, and if so, reallocating or extending the array, which can be costly in terms of performance due to the need to copy the entire array to a new, larger array. This realloc function extends the capacity of the array by a constant value, providing dynamic growth. Additionally, using arrays implies a predefined type, so when reallocating, type casting is necessary, which could introduce potential issues or require additional handling for type safety .

The HashMap's get method utilizes the lists by first checking if the keys list contains the specified key. If the key exists, it retrieves the index of this key using the indexOf method and then uses this index to fetch the corresponding value from the values list. This approach reveals that key-value relationship maintenance relies on synchronized indexing between the keys and values lists, meaning that every key's associated value is stored at the same index position in the values list, ensuring accurate retrieval .

The presented HashMap implementation shares some functional similarities with Java's built-in HashMap, such as storing key-value pairs and using methods like put and get. However, it diverges in several ways due to its simplistic linear data structure basis, like relying on two separate lists using array-backed storage. Unlike Java's HashMap, which uses a more efficient hash table approach for constant-time performance, this implementation faces potential inefficiencies due to its dependence on list traversal for operations like contains and indexOf, leading to linear-time complexity in worst-case scenarios. Additionally, this approach does not support rehashing or collision resolution typically handled in Java HashMaps, which suggest potential limitations in scalability and efficiency compared to optimized Java implementations .

The implementation utilizes two separate lists, one for keys and the other for values, both backed by arrays. The keys list is of type UniqueList, which ensures uniqueness by only adding elements if they are not already contained in the list. This prevents duplicate keys. On the other hand, the values list is of type RegularList, which allows duplicates, meaning the values can be duplicated. The correspondence between keys and values is maintained by using matching indices in both lists .

The UniqueList and RegularList classes ensure proper functioning of the HashMap by managing the storage and organization of keys and values, respectively. UniqueList is responsible for ensuring that each key is unique, thus preventing duplicates, which is fundamental for a key-value pair structure like HashMap. Meanwhile, RegularList allows for the storage of values, including duplicates, providing the flexibility needed to associate multiple values with different keys. These specialized list classes support the HashMap's requirements by implementing necessary operations such as add, get, and contains, tailored to the rules of key uniqueness and value flexibility .

The 'realloc' method enhances the functionality of lists by allowing them to increase in capacity dynamically. This method is invoked when the list is full (i.e., when attempting to add an element to an already full array). By copying the elements to a new array with an increased length, the 'realloc' method resolves size constraints that would otherwise limit the addition of new elements. This ensures that the list can continue to operate efficiently without crashing due to overflow, supporting the dynamic nature required by a HashMap where entries are modified frequently .

The put method contributes to data integrity by first attempting to add the key to the UniqueList, which ensures that it is unique. If the key is successfully added, indicating it wasn't previously present, it then adds the corresponding value to the RegularList. This method only adds new entries if the key is not already in the list, thus maintaining a consistent one-to-one correspondence between each unique key and its value, ensuring that values are only associated with newly added keys .

You might also like