Ybadoo - Soluções em Software Livre
Tutoriais
Programação Orientada a Objetos

A classe java.util.Map da API de coleções de Java permite que sejam armazenados pares de objetos (chave e valor) em uma de suas implementações (as mais conhecidas são HashMap e TreeMap). No entanto, estas classes não possuem um construtor que receba como parâmetro uma matriz de duas linhas e que monte o mapa usando a primeira linha como chave e a segunda como coluna. Desenvolva um adaptador (dica: use Adapter de classe) que tenha este construtor.

 

Diagrama de classes
Diagrama de classes da solução em Java

Arquivo HashMapAdapter.java

/**
 * Copyright (C) 2009/2018 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * Classe responsavel pela adaptacao da classe HashMap a interface Map, com
 * a inclusao de um novo construtor
 *
 * Target  - Map
 * Adaptee - HashMap
 * Adapter - HashMapAdapter
 */
public class HashMapAdapter<K> extends HashMap<K, K>
  implements Map<K, K>, Cloneable, Serializable
{
  /**
   * Identificador de serializacao da classe
   */
  private static final long serialVersionUID = 1L;

  /**
   * Constructs an empty HashMap with the default initial capacity (16) and
   * the default load factor (0.75)
   */
  public HashMapAdapter()
  {
    super();
  }

  /**
   * Constructs an empty HashMap with the specified initial capacity and the
   * default load factor (0.75)
   *
   * @param initialCapacity the initial capacity
   * @throws IllegalArgumentException if the initial capacity is negative
   */
  public HashMapAdapter(int initialCapacity) throws IllegalArgumentException
  {
    super(initialCapacity);
  }

  /**
   * Constructs an empty HashMap with the specified initial capacity and
   * load factor
   *
   * @param initialCapacity the initial capacity
   * @param loadFactor the load factor
   * @throws IllegalArgumentException if the initial capacity is negative or
   *         the load factor is nonpositive
   */
  public HashMapAdapter(int initialCapacity, float loadFactor)
    throws IllegalArgumentException
  {
    super(initialCapacity, loadFactor);
  }

  /**
   * Construir um hashMap com os valores armazenados numa matriz de duas
   * linhas
   *
   * @param matrix matriz a ser carregada para o HashMap
   * @throws IllegalArgumentException se a matriz nao tiver duas linhas
   * @throws NullPointerException se a matriz e nula
   */
  public HashMapAdapter(K[][] matrix)
    throws IllegalArgumentException, NullPointerException
  {
    super();

    if(matrix == null)
    {
      throw new NullPointerException("Matriz nula");
    }

    if(matrix.length != 2)
    {
      throw new IllegalArgumentException("Matriz não tem duas linhas");
    }

    if(matrix[0].length != matrix[1].length)
    {
      throw new IllegalArgumentException("Linhas de comprimento diferente");
    }

    for(int column = 0; column < matrix[0].length; column++)
    {
      put(matrix[0][column], matrix[1][column]);
    }
  }

  /**
   * Constructs a new HashMap with the same mappings as the specified Map.
   *
   * @param map the map whose mappings are to be placed in this map
   * @throws NullPointerException if the specified map is null
   */
  public HashMapAdapter(Map<? extends K, ? extends K> map)
    throws NullPointerException
  {
    super(map);
  }
}

Arquivo TreeMapAdapter.java

/**
 * Copyright (C) 2009/2018 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.io.Serializable;
import java.util.Comparator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Classe responsavel pela adaptacao da classe TreeMap a interface Map,
  * com a inclusao de um novo construtor
 *
 * Target  - Map
 * Adaptee - TreeMap
 * Adapter - TreeMapAdapter
 */
public class TreeMapAdapter<K> extends TreeMap<K, K>
  implements Map<K, K>, Cloneable, Serializable
{
  /**
   * Identificador de serializacao da classe
   */
  private static final long serialVersionUID = 1L;

  /**
   * Constructs a new, empty tree map, using the natural ordering of its
   * keys
   */
  public TreeMapAdapter()
  {
    super();
  }

  /**
   * Constructs a new, empty tree map, ordered according to the given
   * comparator
   *
   * @param comparator the comparator that will be used to order this map.
   *        If null, the natural ordering of the keys will be used
   */
  public TreeMapAdapter(Comparator<? super K> comparator)
  {
    super(comparator);
  }

  /**
   * Construir um hashMap com os valores armazenados numa matriz de duas
   * linhas
   *
   * @param matrix matriz a ser carregada para o HashMap
   * @throws IllegalArgumentException se a matriz nao tiver duas linhas
   * @throws NullPointerException se a matriz e nula
   */
  public TreeMapAdapter(K[][] matrix)
    throws IllegalArgumentException, NullPointerException
  {
    super();

    if(matrix == null)
    {
      throw new NullPointerException("Matriz nula");
    }

    if(matrix.length != 2)
    {
      throw new IllegalArgumentException("Matriz não tem duas linhas");
    }

    if(matrix[0].length != matrix[1].length)
    {
      throw new IllegalArgumentException("Linhas de comprimento diferente");
    }

    for(int column = 0; column < matrix[0].length; column++)
    {
      put(matrix[0][column], matrix[1][column]);
    }
  }

  /**
   * Constructs a new tree map containing the same mappings as the given
   * map, ordered according to the natural ordering of its keys
   *
   * @param map the map whose mappings are to be placed in this map
   * @throws ClassCastException if the keys in m are not Comparable,
   *         or are not mutually comparable
   * @throws NullPointerException if the specified map is null
   */
  public TreeMapAdapter(Map<? extends K, ? extends K> map)
    throws ClassCastException, NullPointerException
  {
    super(map);
  }

  /**
   * Constructs a new tree map containing the same mappings and using the
   * same ordering as the specified sorted map
   *
   * @param map the sorted map whose mappings are to be placed in this map,
   *        and whose comparator is to be used to sort this map
   * @throws NullPointerException if the specified map is null
   */
  public TreeMapAdapter(SortedMap<K, ? extends K> map)
    throws NullPointerException
  {
    super(map);
  }
}

Arquivo Application.java

/**
 * Copyright (C) 2009/2018 - Cristiano Lehrer (cristiano@ybadoo.com.br)
 *                  Ybadoo - Solucoes em Software Livre (www.ybadoo.com.br)
 *
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 1.3
 * or any later version published by the Free Software Foundation; with
 * no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU
 * Free Documentation License".
 */

package com.ybadoo.tutoriais.poo;

import java.util.Map;

/**
 * Classe responsavel pela execucao do padrao Adapter
 */
public class Application
{
  /**
   * Metodo principal da linguagem de programacao Java
   * 
   * @param args argumentos da linha de comando (nao utilizado)
   */
  public static void main(String[] args)
  {
    Integer[][] matrix = new Integer[][]{{1, 2, 3, 4, 5}, {1, 4, 9, 16, 25}};
    
    Map<Integer, Integer> hashMap = new HashMapAdapter<Integer>(matrix);
    
    System.out.println("Elementos armazenados no HashMap");
    
    for(Integer key: hashMap.keySet())
    {
      System.out.println(key + " : " + hashMap.get(key));
    }
    
    System.out.println();
    
    Map<Integer, Integer> treeMap = new TreeMapAdapter<Integer>(matrix);
    
    System.out.println("Elementos armazenados no TreeMap");
    
    for(Integer key: treeMap.keySet())
    {
      System.out.println(key + " : " + treeMap.get(key));
    }
  }
}

Saída da solução em Java

Elementos armazenados no HashMap
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25

Elementos armazenados no TreeMap
1 : 1
2 : 4
3 : 9
4 : 16
5 : 25