I have a class that stores objects in lists. I have 3 different types of lists and I want to save the object in their respective list. As you can see, I have to repeat the method 3 times, once for each type, although in each case, the method does exactly the same thing.
Question:
Is there a way to write the same functionality with just one method using for example generics or interface?
Original code:
@Repository
public class ItemsInMemoryDao {
static List<MyCompany> companies = new ArrayList<>();
static List<Financial> financials = new ArrayList<>();
static List<Stock> stocks = new ArrayList<>();;
// TODO: Rewrite using generics or interface?
static void saveCompany(MyCompany company) {
companies.add(company);
}
static void saveFinancial(Financial financial) {
financials.add(financial);
}
static void saveStock(Stock stock) {
stocks.add(stock);
}
}
Requested state:
@Repository
public class ItemsInMemoryDao {
static List<MyCompany> companies = new ArrayList<>();
static List<Financial> financials = new ArrayList<>();
static List<Stock> stocks = new ArrayList<>();;
static void save(Object object) {
// implementation here
}
}
java-native-interface)? Did you even read the description of the tag when you selected it?instanceofkeyword to identify the object type. However, your structuring looks like it'd benefit from keeping the current setup but maybe adjusting the method names to be the same so it's overloaded and better follows the "tell, don't ask" principle.ItemsInMemoryDao.save()would know at what index an entity is saved. I assume you're considering editing your question to specify that an acceptable answer must support index-based lookup? Correct? TIA.