简体   繁体   中英

how to return objects from hashmap

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

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() ).

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());
}

There is no return directly you can use like that

for (Car c : hm.values()) {
System.out.printf(c);} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM