How to get an object from a HashMap in Java

I'm trying to get the speed of a test object from a HashMap when specifying a key, but I'm not quite sure how to do this. I tried this way, but its wrong:

hash.values().getSpeed(); 

Any help? Thanks

 class Test { private String id; private String name; private int speed; public Test(String id, String name, int speed) { this.id = id; this.name = name; this.speed = speed; } public String getId() { return id; } public String getName() { return name; } public int getSpeed() { return speed; } } public class Driver { public static void main(String[] args) { HashMap<String, Test> hash = new HashMap<String, Test>(); Test c1; Test c2; c1 = new Test("Z", "B", 4); c2 = new Test("Y", "D", 7); hash.put("A", c1); hash.put("C", c2); } } 
+6
source share
6 answers
 Test c1; Test c2; c1 = new Test("Z", "B", 4); c2 = new Test("Y", "D", 7); hash.put("A", c1); hash.put("C", c2); Test getC1 = (Test)hash.get("A"); Test getC2 = (Test)hash.get("C"); 
+9
source

The values ​​() method returns a collection of values ​​contained in a HashMap object. You can use for loop to move the collection of values.

 for(Test t:hash.values()) { System.out.println(t.getSpeed()); } 
+2
source

There is a method in the map interface with the following signature type + return:

 E get(T key); 
+1
source

hash.get("A") or more generally: hash.get(key) , where key was the first argument to the hash.put(key, value) call.

+1
source

get is the opposite of put . So just hash.get("C"); will give you c1 etc.

I suggest you learn the Javadoc from classes that you use more carefully before publishing.

0
source
 public class Driver { public static void main(String[] args) { HashMap<String, Test> hash = new HashMap<String, Test>(); Test c1; Test c2; c1 = new Test("A", "Maruthi", 4); c2 = new Test("B", "Toyota", 7); hash.put("A", c1); hash.put("B", c2); for(Test t:hash.values()) { System.out.println(t.getSpeed() + " " + t.getId() + " " + t.getName()); } } } 
-1
source

Source: https://habr.com/ru/post/899854/


All Articles