Java - Contar valores repetidos por medio de la estructura Hashtable

 
Vista:
sin imagen de perfil

Contar valores repetidos por medio de la estructura Hashtable

Publicado por Jose (1 intervención) el 11/10/2017 05:39:40
Hola.. Soy nuevo en el foro y siguiendo el ejercicio de Vehiculo... Crea una clase con el método main donde se introduzcan 5000 vehículos en una lista de tipo estático List. El atributo tipo debe establecerse para cada objeto de forma aleatoria. A continuación, el programa debe mostrar un resumen de cuántos vehículos hay de cada tipo.

El problema que tengo es:
al contar cuantos elementos repetidos tengo ya sea... Coche, Camión, Furgoneta o Moto me encontré con un fragmento de código en el que me llamo la atención a través del estructura Hashtable, sin embargo tengo problemas en la implementacion. ¿Como podria contar los elementos repetidos implementando el metodo hastable?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package tipo.vehiculo;
 
+++++CODIGO VEHICULO
public class Vehiculo {
	private int idVehiculo;
	private String tipo;
 
	public Vehiculo(int idVehiculo,String tipo) {
		this.idVehiculo=idVehiculo;
		this.tipo=tipo;
	}
 
	public int getIdVehiculo() {
		return idVehiculo;
	}
	public String getTipo() {
		return tipo;
	}
 
@Override
public String toString() {
	return "Resumen lista inicial: hay ";
}
}

+++++++CODIGO MAIN
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package tipo.vehiculo;
 
import java.util.*;
 
public class Call {
 
	public static void main(String[] args) {
		String[] Vehiculos= {"Coche","Camion","Furgoneta","Moto"};
 
 
		List<Vehiculo>listArray = new ArrayList<Vehiculo>();
		List<Vehiculo>linkedList = new LinkedList<Vehiculo>();
 
 
		for(int i = 0; i<5000; i++) {
			listArray.add(new Vehiculo(i, Vehiculos[((int)Math.random()*4)]));
			linkedList.add(new Vehiculo(i, Vehiculos[(int)Math.random()*4]));
		}
 
		Hashtable hashlista = new Hashtable();
		hashlista = repetidos(listArray);
	}
 
	private static Hashtable repetidos(ArrayList lista) {
		Hashtable hashlista = new Hashtable();
		for(Object item: lista) {
			if(hashlista.containsKey(item)) {
				hashlista.put(item, (Integer)hashlista.get(item)+1);
			}else {
				hashlista.put(item, 1);
			}
		}
 
		return hashlista;
	}
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder