I created a class and made 57 objects from it, each one has specific ID number.
Can I create a method which returns an object using an ID as the argument?
For example, assume the name of my class is Things and I made two object from it called apple and dog, they have IDs 1 and 2.
Things.java:
class Things {
private String name;
private int ID;
public Things(String name, int ID) {
this.name = name;
this.ID = ID;
}
}
Main.java:
class Main {
public static void main(String[] args) {
Things apple = new Things("apple", 1);
Things dog = new Things("dog", 2);
}
}
in this example I want to create a method in class "Things" which returns object apple if I use 1 as argument and object dog if I use 2 .
Map<Integer,Things>like <id,object> can be used; see docs.oracle.com/javase/8/docs/api/java/util/Map.htmlThingsinstance from where? You have nothing that containsappleanddog.Thingsbut two instances ofThing:appleanddog. EachThingonly knows itself, it has no idea that there is a secondThing. Use theThingRepositoryapproach outlined in the answer below.