0

I have a problem when adding HashMaps with custom objects to an ArrayList. Here you are the HashMaps definitions:

static Map<Long, Supermarket> supermarkets = new HashMap<Long, Supermarket>();
static Map<Long, Product> products = new HashMap<Long, Product>();

And this is the ArrayList definition:

static ArrayList<HashMap> supemarketsAndProducts = new ArrayList<HashMap>();

I also tried with a List with same results. Product is a class which creates product objects. Supermarket is the class which creates supermarkets objects.

The problem is when adding elements to de ArrayList. I am trying on this way:

supemarketsAndProducts.add(supermarkets);
supemarketsAndProducts.add(products);

I need an structure made of those hashmaps (supermarkets and products) because I need this class returning both hashmaps structures. What am I doing wrong? Any solution/workaround to return the hashmaps I need?

Thanks and regards.

Edited: Here you are the full code (but it is too long: it is a customized SAX parser which is called from another class, and variables names are in spanish).

package parsers;

import java.io.*;
import java.util.*;
import java.math.BigDecimal;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.*;
import org.xml.sax.SAXParseException;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;

public class LectorXML extends DefaultHandler {

  static Map<Long, Supermercado> supermercados = new HashMap<Long, Supermercado>();
  static Map<Long, Producto> productos = new HashMap<Long, Producto>();
  static List<Map> supermercadosYproductos = new ArrayList<Map>();
  static Long numeroSupermercado = 0L;
  static Long numeroProducto = 0L;

  private final XMLReader xr;
  boolean bfname = false;
  boolean blname = false;
  boolean bnname = false;
  boolean bsalary = false;
  boolean bs_id = false;
  boolean bnombre = false;
  boolean bdireccion = false;
  boolean bpoblacion = false;
  boolean bprovincia = false;
  boolean blongitud = false;
  boolean blatitud = false;
  boolean bfavorito = false;
  boolean btelefono = false;
  boolean bp_id = false;
  boolean bcodigobarras = false;
  boolean bnombrep = false;
  boolean bfabricante = false;
  boolean bcategoria_1 = false;
  boolean bcategoria_2 = false;
  boolean bcategoria_3 = false;
  boolean bprecio_1 = false;
  boolean bfecha_1 = false;
  boolean bprecio_2 = false;
  boolean bfecha_2 = false;
  boolean bsupermercado = false;
  boolean bdireccion_supermercado = false;
  boolean bpoblacion_supermercado = false;
  boolean bcomprar = false;

  public LectorXML() throws SAXException {
    xr = XMLReaderFactory.createXMLReader();
    xr.setContentHandler(this);
    xr.setErrorHandler(this);
  }

  public void leer(final String archivoXML)
          throws FileNotFoundException, IOException, SAXException {
    FileReader fr = new FileReader(archivoXML);
    xr.parse(new InputSource(fr));
  }

//  @Override
//  public void startDocument() {
//    System.out.println("Comienzo del Documento XML");
//  }
//  @Override
//  public void endDocument() {
//    System.out.println("Final del Documento XML");
//  }
  @Override
  public void startElement(String uri, String name,
          String qName, Attributes attributes) throws SAXException {
//    System.out.println("tElemento: " + name);
//          System.out.println("Start Element :" + qName);

    for (int i = 0; i < attributes.getLength(); i++) {
//            System.out.println("qName: ------  " + qName + " ---------");
//            System.out.println("ttAtributo: "
//                    + attributes.getLocalName(i) + " = " + attributes.getValue(i));
      if (attributes.getValue(i).equalsIgnoreCase("s_id")) {
        bs_id = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("nombre")) {
//              System.out.println("Nombre del supermercado: " + attributes.getValue(i));
        bnombre = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("direccion")) {
//              System.out.println("Dirección del supermercado: " + attributes.getValue(i));
        bdireccion = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("poblacion")) {
//              System.out.println("Población del supermercado: " + attributes.getValue(i));
        bpoblacion = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("provincia")) {
//              System.out.println("Provincia del supermercado: " + attributes.getValue(i));
        bprovincia = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("longitud")) {
//              System.out.println("Longitud del supermercado: " + attributes.getValue(i));
        blongitud = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("latitud")) {
//              System.out.println("Latitud del supermercado: " + attributes.getValue(i));
        blatitud = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("favorito")) {
//              System.out.println("¿Supermercado favorito?: " + attributes.getValue(i));
        bfavorito = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("telefono")) {
//              System.out.println("Teléfono del supermercado: " + attributes.getValue(i));
        btelefono = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("p_id")) {
//              System.out.println("Id del producto: " + attributes.getValue(i));
        bp_id = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("codigobarras")) {
//              System.out.println("Código de barras del producto: " + attributes.getValue(i));
        bcodigobarras = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("nombrep")) {
//              System.out.println("Nombre del producto: " + attributes.getValue(i));
        bnombrep = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("fabricante")) {
//              System.out.println("Fabricante del producto: " + attributes.getValue(i));
        bfabricante = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("categoria_1")) {
//              System.out.println("Categoría del producto: " + attributes.getValue(i));
        bcategoria_1 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("categoria_2")) {
//              System.out.println("Categoría 2 del producto: " + attributes.getValue(i));
        bcategoria_2 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("categoria_3")) {
//              System.out.println("Categoría 3 del producto: " + attributes.getValue(i));
        bcategoria_3 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("precio_1")) {
//              System.out.println("Precio del producto: " + attributes.getValue(i));
        bprecio_1 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("fecha_1")) {
//              System.out.println("Fecha del producto: " + attributes.getValue(i));
        bfecha_1 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("precio_2")) {
//              System.out.println("Precio 2 del producto: " + attributes.getValue(i));
        bprecio_2 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("fecha_2")) {
//              System.out.println("Fecha 2 del producto: " + attributes.getValue(i));
        bfecha_2 = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("supermercado")) {
//              System.out.println("Nombre del supermercado del producto: " + attributes.getValue(i));
        bsupermercado = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("direccion_supermercado")) {
//              System.out.println("Dirección del supermercado del producto: " + attributes.getValue(i));
        bdireccion_supermercado = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("poblacion_supermercado")) {
//              System.out.println(" Población del supermercado del producto: " + attributes.getValue(i));
        bpoblacion_supermercado = true;
      }
      if (attributes.getValue(i).equalsIgnoreCase("comprar")) {
//              System.out.println(" Comprar el producto? " + attributes.getValue(i));
        bfavorito = true;
      }
    }
  }

//  @Override
//  public void endElement(String uri, String name,
//          String qName) throws SAXException {
//    System.out.println("tFin Elemento: " + name);
//  }
  @Override
  public void characters(char[] ch, int start, int length)
          throws SAXException {
//    System.out.println(new String(ch, start, length));

    Supermercado supermercado = new Supermercado();
    Producto producto = new Producto();

    if (bs_id) {
      String idSupermercado = new String(ch, start, length);
      System.out.println("Id del supermercado: " + idSupermercado);
      bs_id = false;
      supermercado.supermercadoId = Long.parseLong(idSupermercado);
    }
    if (bnombre) {
      String nombreSupermercado = new String(ch, start, length);
      System.out.println("Nombre del supermercado: " + nombreSupermercado);
      bnombre = false;
      supermercado.nombre = nombreSupermercado;
    }
    if (bdireccion) {
      String direccionSupermercado = new String(ch, start, length);
      System.out.println("Dirección del supermercado: " + direccionSupermercado);
      bdireccion = false;
      supermercado.direccion = direccionSupermercado;
    }
    if (bpoblacion) {
      String poblacionSupermercado = new String(ch, start, length);
      System.out.println("Población del supermercado: " + poblacionSupermercado);
      bpoblacion = false;
      if (poblacionSupermercado.equalsIgnoreCase(""))
        supermercado.poblacion = null;
      else supermercado.poblacion = poblacionSupermercado;
    }
    if (bprovincia) {
      String provinciaSupermercado = new String(ch, start, length);
      System.out.println("Provincia del supermercado: " + provinciaSupermercado);
      bprovincia = false;
      supermercado.provincia = provinciaSupermercado;
    }
    if (blongitud) {
      String longitudSupermercado = new String(ch, start, length);
      System.out.println("Longitud del supermercado: " + longitudSupermercado);
      blongitud = false;
      if (longitudSupermercado.equalsIgnoreCase("0"))
        supermercado.longitud = null;
      else supermercado.longitud = Double.parseDouble(longitudSupermercado);
    }
    if (blatitud) {
      String latitudSupermercado = new String(ch, start, length);
      System.out.println("Latitud del supermercado: " + latitudSupermercado);
      blatitud = false;
      if (latitudSupermercado.equalsIgnoreCase("0"))
        supermercado.latitud = null;
      else supermercado.latitud = Double.parseDouble(latitudSupermercado);
    }
    if (bfavorito) {
      String supermercadoFavorito = new String(ch, start, length);
      System.out.println("Supermercado favorito? " + supermercadoFavorito);
      bfavorito = false;
      if (supermercadoFavorito.equals("0")) {
        supermercado.favorito = false;
      } else if (supermercadoFavorito.equals("1")) {
        supermercado.favorito = true;
      }
    }
    if (btelefono) {
      String telefonoSupermercado = new String(ch, start, length);
      System.out.println("Teléfono del supermercado: " + telefonoSupermercado);
      btelefono = false;
      if (telefonoSupermercado.equalsIgnoreCase("0"))
        supermercado.telefono = null;
      else supermercado.telefono = telefonoSupermercado;
    }
    if (bp_id) {
      String idProducto = new String(ch, start, length);
      System.out.println("Id del producto: " + idProducto);
      bp_id = false;
      producto.productoId = Long.parseLong(idProducto);
    }
    if (bcodigobarras) {
      String codigoBarras = new String(ch, start, length);
      System.out.println("Código de barras del producto: " + codigoBarras);
      bcodigobarras = false;
      if (codigoBarras.equalsIgnoreCase("0"))
        producto.codigobarras = null;
      else producto.codigobarras = codigoBarras;
    }
    if (bnombrep) {
      String nombreProducto = new String(ch, start, length);
      System.out.println("Nombre del producto: " + nombreProducto);
      bnombrep = false;
      producto.nombre = nombreProducto;
    }
    if (bfabricante) {
      String fabricanteProducto = new String(ch, start, length);
      System.out.println("Fabricante del producto: " + fabricanteProducto);
      bfabricante = false;
      if (fabricanteProducto.equalsIgnoreCase(""))
        producto.fabricante = null;
      else producto.fabricante = fabricanteProducto;
    }
    if (bcategoria_1) {
      String categoria1 = new String(ch, start, length);
      System.out.println("Categoría del producto: " + categoria1);
      bcategoria_1 = false;
      producto.categoria_1 = categoria1;
    }
    if (bcategoria_2) {
      String categoria2 = new String(ch, start, length);
      System.out.println("Categoría 2 del producto: " + categoria2);
      bcategoria_2 = false;
      if (categoria2.equalsIgnoreCase(""))
        producto.categoria_2 = null;
      else producto.categoria_2 = categoria2;
    }
    if (bcategoria_3) {
      String categoria3 = new String(ch, start, length);
      System.out.println("Categoría 3 del producto: " + categoria3);
      bcategoria_3 = false;
      if (categoria3.equalsIgnoreCase(""))
        producto.categoria_3 = null;
      else producto.categoria_3 = categoria3;
    }
    if (bprecio_1) {
      String precio1 = new String(ch, start, length);
      System.out.println("Precio del producto: " + precio1);
      bprecio_1 = false;
      if (precio1.equalsIgnoreCase("0"))
        producto.precio_1 = null;
      else producto.precio_1 = Double.parseDouble(precio1);
    }
    if (bfecha_1) {
      String fecha1 = new String(ch, start, length);
      System.out.println("Fecha del producto: " + fecha1);
      bfecha_1 = false;
      if (fecha1.equalsIgnoreCase("0"))
        producto.fecha_1 = null;
      else producto.fecha_1 = ConvertirFecha.conversion(fecha1);
    }
    if (bprecio_2) {
      String precio2 = new String(ch, start, length);
      System.out.println("Precio 2 del producto: " + precio2);
      bprecio_2 = false;
      if (precio2.equalsIgnoreCase("0"))
        producto.precio_2 = null;
      else producto.precio_2 = Double.parseDouble(precio2);
    }
    if (bfecha_2) {
      String fecha2 = new String(ch, start, length);
      System.out.println("Fecha 2 del producto: " + fecha2);
      bfecha_2 = false;
      if (fecha2.equalsIgnoreCase("0"))
        producto.fecha_2 = null;
      else producto.fecha_2 = ConvertirFecha.conversion(fecha2);
    }
    if (bsupermercado) {
      String nombreSupermercadoProducto = new String(ch, start, length);
      System.out.println("Nombre del supermercado del producto: " + nombreSupermercadoProducto);
      bsupermercado = false;
      producto.supermercado = nombreSupermercadoProducto;
    }
    if (bdireccion_supermercado) {
      String direccionSupermercadoProducto = new String(ch, start, length);
      System.out.println("Dirección del supermercado del producto: " + direccionSupermercadoProducto);
      bdireccion_supermercado = false;
      producto.direccion_supermercado = direccionSupermercadoProducto;
    }
    if (bpoblacion_supermercado) {
      String poblacionSupermercadoProducto = new String(ch, start, length);
      System.out.println("Población del supermercado del producto: " + poblacionSupermercadoProducto);
      bpoblacion_supermercado = false;
      if (poblacionSupermercadoProducto.equalsIgnoreCase(""))
        producto.poblacion_supermercado = null;
      else producto.poblacion_supermercado = poblacionSupermercadoProducto;
    }
    if (bcomprar) {
      String comprarProducto = new String(ch, start, length);
      System.out.println(" Comprar el producto? " + comprarProducto);
      bcomprar = false;
      if (comprarProducto.equals("0")) {
        producto.comprar = false;
      } else if (comprarProducto.equals("1")) {
        producto.comprar = true;
      }
    }
    if (supermercado.supermercadoId != null)
      supermercados.put(numeroSupermercado, supermercado);
    if (producto.productoId != null)
      productos.put(numeroProducto, producto);
  }
  supermercadosYproductos.add(supermercados);
  supermercadosYproductos.add(productos);
}
6
  • What problem are you facing? Please specify clearly. And please post real code. Commented Nov 14, 2012 at 9:23
  • remove the Generics <HashMap> from the supermarketsAndproducts. so your list will be generic accepting both the hashmaps! Commented Nov 14, 2012 at 9:24
  • Could you not return an Object of type SupermarketStock or similar, that combines a Supermarket with some Products? Commented Nov 14, 2012 at 9:28
  • @RohitJain that's the real code (after translating variables names from spanish to english). Commented Nov 14, 2012 at 9:36
  • @madhairsilence problem perssits :( Commented Nov 14, 2012 at 9:37

2 Answers 2

1

You must use wildcards to cover the fact that you are adding disparate maps into the list:

static List<Map<Long, ?>> supemarketsAndProducts = new ArrayList<>();

Of course, when you retrieve an object from this list, you won't have a static type for it. That would be impossible to achieve. You'll need to perform an unchecked cast, and there goes your type safety.

Sign up to request clarification or add additional context in comments.

3 Comments

It doesn'w tork on jdk1.6, just on 1.7. Any idea for 1.6? Thanks.
Just copy the type parameters from the left-hand side into the right-hand side.
It doesn't work. I get: <identifier> expected package supemarketsAndProducts does not exist when i try to save it in this way supemarketsAndProducts.add(0L, supermarkets);. The declaration is static List<Map<Long, ?>> supemarketsAndProducts = new ArrayList<Map<Long, ?>>();
0

Well, finally I resolved the issue on my own. The definition was ok (original code, no translations for variables for not wasting more time haha):

static List<Map> supermercadosYproductos = new ArrayList<Map>();

The problem was that I was trying to save products and supermarkets in the wrong place: it should be in my public List<Map> leer(final String archivoXML) method in this way:

if (!supermercadosYproductos.isEmpty()) {
  supermercadosYproductos.add(supermercados);
  supermercadosYproductos.add(productos);
  return supermercadosYproductos;
}
else return null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.