Reputation: 95
Car c1 = new Car();
Car c2 = new Car();
HashMap<String,Car> hm= new HashMap<String, Car>();
hm.put("Ford",c1);
hm.put("Volvo",c2);
How do I iterate to get only the values(only name) to be printed?
Out should be:
c1
c2
Not the below :
c1@13efr5t4
c2@234fvdf4
Upvotes: 0
Views: 3201
Reputation: 19211
Step 1: First you have to override the toString()
method in the Car
class.
public class Car {
// attribute
private final String name;
// Constructor
public Car(final String name) {
this.name = name;
}
// getter
public String getName() {
return name;
}
// Override of toString
@Override
public String toString() {
return name;
}
}
If you don't implement a proper toString
-method the method from Object
will be used when you invoke System.out.println(car)
, and that implementation returns the following (which is what you see in your current printing):
return getClass().getName() + "@" + Integer.toHexString(hashCode());
The way you create a new Car
from the class above is to invoke the following constructor:
Car c = new Car("Ford");
Step 2: iterate using a loop.
When using a Map
you can choose to iterate over the keys, the values or the entries. All of these three alternatives returns some kind of Collection
. Collections
can be iterated using various types of loops.
// Standard Java 5+ foreach-loop that prints the values
for (Car c : hm.values()) {
System.out.println(c);
}
// Loop using an iterator that prints the keys
for (Iterator<Car> itr = hm.keys().iterator(); itr.hasNext(); ) {
System.out.println(itr.next());
}
// Or a Java 8 loop
hm.values().forEach(System.out::println);
If you instead want the keys of the map ("Ford", "Volvo") you can replace the call to values()
with a call to keySet()
. For the entries, invoke the method entrySet()
which returns a Map.Entry
object where you can get both the key (via getKey()
and the value via getValue()
).
Upvotes: 3
Reputation: 5023
HashMap<String,Car> hm= new HashMap<String, Car>();
hm.put("Ford",c1);
hm.put("Volvo",c2);
In your hash map you are putting objects not string.
When you pare printing your objects as string it is geving you output
c1@13efr5t4
c2@234fvdf4
If you have want to print suppose car name then use following way or you have to implement toString()
method in your Car
which will give you your expected output.
for (Car c : hm.values()) {
System.out.println(c.getCarName());
}
Upvotes: 0
Reputation: 315
There is no return directly you can use like that
for (Car c : hm.values()) {
System.out.printf(c);}
Upvotes: -2