The title may be confusing, but I will try to explain it with the following example.
I have defined two different types of classes, CDMarker and PDLMarker. In a processing method as below, I create a arraylist for one of the types and use a foreach loop to analyze each one of them.
ArrayList<CDMarker> cdMarkers = new ArrayList<CDMarker>();
......
for (CDMarker marker : cdMarkers) {
.....
}
Which class to use depends on user input. For example with condition1, CDMarker is the type to use. Condition2, PDLMarker.
Instead of having code like:
if condition1
{
ArrayList<CDMarker> cdMarkers = new ArrayList<CDMarker>();
......
for (CDMarker marker : cdMarkers) {
.....
}
}
if condition2
{
ArrayList<PDLMarker> pdlMarkers = new ArrayList<PDLMarker>();
......
for (PDLMarker marker : pdlMarkers) {
.....
}
}
can I have a fake class (Marker) which can represent either type? Something like:
if condition1
Marker = CDMarker;
if condition2
Marker = PDLMarker;
ArrayList<Marker> markers = new ArrayList<Marker>();
for (Marker marker : markers) {
.....
}
Edit: Looks like interface is the way to go. The problem is that the creation of the List of CDMarker/PDLMarker is done in a method:
if condition1
List<Marker> markers = writeCDMarker(sheet, dir);
if condition2
List<Marker> markers = writePDLMarker(sheet, dir);
public static List<PDLMarker> writePDLMarker(HSSFSheet sheet, File dir) {
List<PDLMarker> pdlMarkers = new ArrayList<PDLMarker>();
....
return pdlMarkers;
}
public static List<CDMarker> writeCDMarker(HSSFSheet sheet, File dir) {
List<CDMarker> cdMarkers = new ArrayList<CDMarker>();
....
return cdMarkers;
}
Now I got an error at line List<Marker> markers = writePDLMarker(sheet, dir); saying
Multiple markers at this line
- Type mismatch: cannot convert from List to List
- Type mismatch: cannot convert from ArrayList to List
How do I fix this?