Java overriding two interfaces, clash of method names - java

I am implementing the Map<V,K> and the Collection<V> interface in one class, but the remove(Object) method occurs in both interfaces, therfore eclipse shows me some errors. The return types are different, one returns boolean and the other V but that doesn't seem to matter.
Is there some way of telling java/eclipse which method is actually being overridden?
EDIT: I have got an interface that all values must implement, it supplies the value with a getKey() method, making it possible to write an add function for the map. But there seems to be no way to let this one class look as a map and a collection at the same time?

No, there is no a direct way.
Actually dynamic binding takes into account the signature excluding the returning type so Java compiler cannot accept the two methods for the same class that have same signature but different return types. If two methods have same names and same parameters than they MUST also have same returning type, unfortunately for you.
The only way is to split the behavior in two different classes and composing them. Maybe a method like Collection<V> asCollection() or something like that.

The Map already has keySet() which is collection of keys. Why do you need the Collection also? If it's so, just do two methods like asMap and asCollecton which do return different types.

No, there isn't a way to resolve such conflicts.
You should consider to use composition and delegation instead of inheritance for at least one of the two interfaces, or you could split the functionality of your class in two classes, it really depends on your concrete problem.

You probably need composition instead of inheritance. Unfortunately Java has no language-level support for that - I mean it can be done but it is unnecessarily laborious.

You need to rethink your design. Fundamentally, a map is different to a collection. Think about the Collection.add() method. Does it make any sense to add an object without a key or a key without a value to a map?
Your best bet (I think and depending on your application) is to implement a map but when you need a collection, use one of its methods to get the set of keys, values or key value pairs.

Related

How to write javadoc for method returning a map with known keys

Lets say i have a method like:
Map<String,Object> getData()
What's a good way to document what keys and values it will contain, assuming list of possible keys and types of objects for those keys are known?
[edit]
Assume I can't/won't change the method in a way that'd require changing other code, how can i still sensibly document it?
I suggest to use an enum that lists those keys (and probably another one for value classes if that makes sense in your case). Assuming that you really know all potential keys up front, that would make the most sense. Going from there: if your keys are really known, and limited, then why are using a string as key? You could as well do Map<EnumForKeys, Object> instead.
The nice thing is that you can put nice javadoc on each of the enum constants; see here. And you know, assuming that the value class is fixed for each different key, you could put a method on that Enum that actually tells you the value class directly.
The next, but far less appealing option would be to have some static List somewhere, that contains all the potential keys.
Edit: given your last comment options are of course pretty limited. In that case, you could still use an Enum to list the potential keys, and put a {#link} into the javadoc of your method. Sure, all of that is "informal" only; but well, better than nothing.

How to create multimap of general datatype value in Java

I want to create a multimap where value could be general data type. For eg:
MultiMap<String,Integer> columnvalueMapList = new MultiMap<String,Integer>();
Here instead of integer, i want to make general data type. How can i do so?
You can use Object as a value type in a Map. However this is rarely a good idea as you will likely end up needing instanceof and casts to make use of the objects you extract.
Often the motivation for this is to be able to store objects of different classes without a common superclass. However a better option in these situations is to use an interface to define the common behaviour for all items in the collection. Then any classes that could be added to the collection must implement that interface. You then declare your collection as, for example, List<CommonInterface>. This is safer, clearer and easier to understand.

Using interfaces over classes

I'm a bit confused about the advice to use the Interface for a Java class, like in this thread: Why should the interface for a Java class be preferred?
I understand why you would want to use the interface: if something changes later you have less code to clean up.
But aren't there cases in which using the Interface would prevent you from being able to take advantage of the performance reason why you chose that particular class in the first place?
For instance, if I have a TreeMap, I assume that I should be able to locate any element in at most O(logn). That's why it has nice methods I can take advantage of like higherEntry(), lowerEntry(), lastEntry().
If I instead reference this TreeMap as a Map, now I believe I am forced to iterate one element at a time through my list in O(n) to locate that entry.
I'm new to Java, so let me know if I'm missing something here.
If I instead reference this TreeMap as a Map, now I believe I am
forced to iterate one element at a time through my list in O(n) to
locate that entry.
No you are not forced to do that. If you are sure that your Map reference is holding a reference to TreeMap, and you want to access specific method of TreeMap, then you can always typecast the Map reference to a TreeMap reference, and then access the appropriate method, like, higherEntry(), lowerEntry().
But, the only caveat is that, you have to be sure that your Map reference is actually pointing to a TreeMap, to avoid getting a ClassCastException at runtime.
This is implied by the fact that, a super class and it's sub classes are covariant in nature. So, you can perform cast between them, provided you are not breaking the rules at runtime (That is having the super class reference holding the reference to some other sub class instance, which is not covariant with the sub class you are casting to).
Now for your example, since the TreeMap also implements the NavigableMap interface, which is a sub interface of Map interface, so you can use it instead of Map interface. So, you can have the advantage of polymorphism, without the need to typecast.
If you want to use methods like higherEntry, lowerEntry, and lastEntry, then just use the NavigableMap interface instead of the Map interface or the TreeMap class.
In general, use interfaces as often as possible, and use the most general interface you can that supports all the operations you'd want to use.

Java Variable type and instantiation

This has been bugging me for a while and have yet to find an acceptable answer. Assuming a class which is either a subclass or implements an interface why would I use the Parent class or Interface as the Type i.e.
List list = new ArrayList();
Vehicle car = new car();
In terms of the ArrayList this now only gives me access to the List methods. If I have a method that takes a List as a parameter then I can pass either a List or an ArrayList to it as the ArrayList IS A List. Obviously within the method I can only use the List methods but I can't see a reason to declare it's type as List. As far as I can see it just restricts me to the methods I'm allow to use elsewhere in the code.
A scenario where List list = new ArrayList() is better than ArrayList list = new ArrayList() would be much appreciated.
You write a program that passes lists around several classes and methods. You now want to use it in a multi threading environment. If you were sensible and declared everything as List, you can now make a single change to one line of code:
List list = Colllections.synchronizedList(new ArrayList());
If you had declared the list as an ArrayList, you would instead have to re-write your entire program. The moral of the story - always program to the least restrictive interface that your code requires.
Using the interface or parent type is generally recommended if you only need the functionality of the parent type. The idea is to explicitly document that you don't really care about the implementation, thus making it easier to swap out the concrete class for a different one later.
A good example are the Java collection classes:
If you always use List, Set etc. instead of e.g. ArrayList, you can later switch from ArrayList to LinkedList if you find that it gives e.g. better performance. To do that, just change the constructors (you don't even have to change them all, you can mix). The rest of the code still sees an instance of List and continues working.
If you actually used ArrayList explicitly, you'd have to change it everywhere it's used. If you don't actually need an ArrayList specifically, there's nothing to be gained from using it over the interface.
That's why it's generally recommended (e.g. in "Effective Java" (J.Bloch), Item 52: "Refer to Objects by their interfaces".) to only use interfaces if possible.
Also see this related question: Why classes tend to be defined as interface nowadays?
The key is exactly that the interface or base class restricts what you can do with the variable. For example, if you refactor your code later to use another implementation of that interface or base class, you won't have anything to fear -- you didn't rely on the actual type's identity.
Another thing is that it often makes reading the code easier, e.g. if your method's return type is List you might find it more readable to return a variable of type List.
An interface specifies a contract (what does this thing do), an implementation class specifies the implementation details (how does it do it).
According to good OOP practice, your application code should not be tied to implementation details of other classes. Using an interface keeps your application loosely coupled (read: Coupling)
Also, using an interface lets client code pass in different implementations and apply the decorator pattern using methods like Collections.synchronizedList(), Collections.unmodifiableList() etc.
A scenario where List list = new
ArrayList() is better than ArrayList
list = new ArrayList() would be much
appreciated.
One concrete example: if it's a field declaration and you have a setList(), which of course should take a List parameter to be flexible.
For local variables (and fields with no setters), there is very little concrete benefit in using the interface type. Many people will do it anyway on general principle.
You were right. In these cases, the variables are fields or local variables, they are not public interface, they are implementation details. Implementation detail should be detailed. You should call an ArrayList an ArrayList, because you just deliberately chose it for your implementation.
People who recycle cliches: look at your post and think a little bit more. It's nonsense.
My previous answer that was downvoted to death:
Use interface or type for variable definition in java?

Typing convention for local collections in Java

I recently ran across a set of code which instantiated local maps as following:
HashMap<String, Object> theMap = new HashMap<String, Object>();
Typically, when I've seen HashMaps used (and used them myself), the local variables are simply Map (the interface), rather than being tied to the specific implementation. Obviously this is required if the Map could potentially be instantiated as various Map types (e.g. accepting a parameter). However, in the case of something like the above where it's defined and instantiated at the same point, is there an underlying reason to only use the interface type, or is it simply style/convention?
(I originally misunderstood the question based on the title, but I've included both type and variable conventions as both are interesting.)
What's important is that it's a map: something you look things up in. The rest is an implementation detail.
I would suggest giving it a semantic name, e.g.
Map<String, Object> nameToSessionMap = ...
... that way when you read the code, you'll know what the keys and values are meant to be.
As for the type of the variable - again, I'd typically use the interface rather than the implementation partly because it indicates I'm not using any members which are specific to the type. I don't want to emphasize the implementation in the code, usually... it means when I do care about the implementation, I can make that more obvious.
Declaring the object as a Map will allow the compiler to protect you from calling methods which are specific to HashMap. This will allow you to substitute another Map implementation in the future without worrying about having method calls which do not exist in the Map interface.
In general people use mostly Map to make the least amount of assumptions on the implementation.
It cannot be that the Classname is used for the additional methods as only clone() is added by HashMap, which has fallen in disuse (for good reasons).
What could be is that the map needs to be Serializable for one reason or another, and the plain Map interface does not extend it, but HashMap does implement it.
Even in this case, it keeps it generic. Coding to interface ensures you are using a Map and not a specific implementation of it.

Categories