I need the following functionality
Given two sorted lists, merge them
I have this skeleton Java code:
public class MergeLists{
public List merge(List l1, List l2){
List l3;
// merge l1, l2 in to l3
return l3;
}
public static void main(){
// populate list1 and list2
MergeLists ml = new MergeLists();
List l3 = ml.merge(l1,l2);
}
}
Is this single method class the right approach? I feel like the almost-empty class is staring at me to say that this is bad design. I initially had List L3 as private member of MergeLists but then I thought, merge(l1,l2) can be called multiple times with the same object, which required l3 to be local to merge(l1,l2). I read that using static method is even worse for code re-usability. Please advise. Thank you.
Classes with only static methods is a common pattern in Java for utility methods. Examples in the standard library include Files, Collections, and Executors. For such utility classes, it's a good idea to make sure that your class cannot be instantiated, to make the intent of the class clear.
Classes without methods (data class) are often accompanied with classes that contain only methods. A typical name for these classes with nothing but methods is SometingService. So you will see a User data class and a UserService class that contain methods to do operations on User objects.
Having two or more methods named the same in the same class is called overloading. It's not overloading if you have the same method name in two different classes.
Yes, we can define multiple methods in a class with the same name but with different types of parameters.
You can do this, but I think you want the merge
method to be static
. This will make sure that you don't have to instantiate it before calling the method. You can just do this:
List l3 = MergeLists.merge(l1,l2);
Additionally, if this is the only method and it's static, you can make the class abstract
which means it cannot be instantiated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With