I need to create generic list that can act as List<ClassA> or List<ClassB> because I have following situation.
if(e instanceof A)
return A;
else
return B
But I want to populate one List Result which can act as either List<ClassA> Result or List<ClassB> Result, am sure we can use generics here but i am not sure how to use it?
Update
All i want to do is that runtime, my List should be populated with proper type, either class A or class B,
if()
{
//data is present in List<ClassA> classAList = new ArrayList<ClassA>();
//return classAList
}
else
{
//return List<ClassB> classBList = new ArrayList<ClassB>();
}
Hope this helps.
So if I understand you correctly, you want to be able to construct a list of ClassA or a list of ClassB depending on if a given object is ClassA or ClassB.
Unfortunately, the return type must allow for either type (you can alternatively create two methods with different return types, but they must have different names). However, this allows you to use listA and listB as their own types before assigning it to the more generic list.
However this is a violation of the SOLID principal, so an alternative might be:
Hope that helps!