I'm teaching myself Java and was hoping for feedback regarding this question:
Write a Java interface with two methods, one that adds two doubles together returning the sum and one that multiplies two doubles together returning the product. Use JavaDoc comments.
Am I missing anything? Is it appropriate to include #return in the JavaDoc comment for the interface?
/**
* This is an interface for basic math.
*/
public interface Math {
/**
* This method will be used to add two doubles.
* #param a a value to be added
* #param b the other value to be added
* #return the sum of the two doubles
*/
public double add(double a, double b);
/**
* This method will be used to multiply two doubles.
* #param a a value
* #param b the other value
* #return the product of the two doubles
*/
public double multiply(double a, double b);
}
Am I missing anything?
There is nothing fundamentally wrong or "missing" from the javadocs in their current form.
Is it appropriate to include #return in the JavaDoc comment for the interface?
It is absolutely appropriate. An interface is a form of API, and meaning of the value returned by an API method is a fundamental aspect of the interface. If the meaning of a method return value is not specified in an interface then a caller of the interface method can't know what to expect. This makes programming to the interface difficult.
Yes, it is appropriate to have #return.
Few things you can improve:
To follow Java coding conventions, start method names with lowercase
(e.g. use add instead of Add).
Have better parameter names. E.g.
use number1, number2 instead of a, b.
Start #param and #return descriptions with uppercase letters (e.g. #param number1 First number).
I thinks it is better to say Returns the addition of two given numbers than This method will be used to add two doubles.
Related
Looking at the implementation for Stream#toList, I just noticed how overcomplicated and suboptimal it seemed.
Like mentioned in the javadoc just above, this default implementation is not used by most Stream implementation, however, it could have been otherwise in my opinion.
The sources
/**
* Accumulates the elements of this stream into a {#code List}. The elements in
* the list will be in this stream's encounter order, if one exists. The returned List
* is unmodifiable; calls to any mutator method will always cause
* {#code UnsupportedOperationException} to be thrown. There are no
* guarantees on the implementation type or serializability of the returned List.
*
* <p>The returned instance may be value-based.
* Callers should make no assumptions about the identity of the returned instances.
* Identity-sensitive operations on these instances (reference equality ({#code ==}),
* identity hash code, and synchronization) are unreliable and should be avoided.
*
* <p>This is a terminal operation.
*
* #apiNote If more control over the returned object is required, use
* {#link Collectors#toCollection(Supplier)}.
*
* #implSpec The implementation in this interface returns a List produced as if by the following:
* <pre>{#code
* Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())))
* }</pre>
*
* #implNote Most instances of Stream will override this method and provide an implementation
* that is highly optimized compared to the implementation in this interface.
*
* #return a List containing the stream elements
*
* #since 16
*/
#SuppressWarnings("unchecked")
default List<T> toList() {
return (List<T>) Collections.unmodifiableList(new ArrayList<>(Arrays.asList(this.toArray())));
}
My idea of what would be better
return (List<T>) Collections.unmodifiableList(Arrays.asList(this.toArray()));
Or even
return Arrays.asList(this.toArray()));
IntelliJ's proposal
return (List<T>) List.of(this.toArray());
Is there any good reason for the implementation in the JDK sources?
The toArray method might be implemented to return an array that is then mutated afterwards, which would effectively make the returned list not immutable. That's why an explicit copy by creating a new ArrayList is done.
It's essentially a defensive copy.
This was also discussed during the review of this API, where Stuart Marks writes:
As written it's true that the default implementation does perform apparently redundant copies, but we can't be assured that toArray() actually returns a freshly created array. Thus, we wrap it using Arrays.asList and then copy it using the ArrayList constructor. This is unfortunate but necessary to avoid situations where someone could hold a reference to the internal array of a List, allowing modification of a List that's supposed to be unmodifiable.
I am new to programming/Java and have been trying to teach myself it the last couple of weeks using some free textbooks and online resources. I thought a good way to learn would be to build a role-laying game I enjoy into a Java program. That being said, I know lots of people don't document their code effectively and want to avoid this being a habit, so I am trying to document everything in as much detail as possible. I cannot figure out if I am documenting this correctly though, even when referencing the Javadoc page, so any help would be appreciated. Basically I have a class 'Character' which implements all the required aspects of a character in this game. As an examplle, I have an enum which is a list of possible ability scores for a character in the game:
/**
* AbilityScores is an enum type containing all the possible ability scores in the game. It is
* utilized by the HashMap {#link #abilities} for the keys with an int being used as the values.
*/
private enum AbilityScores {
STRENGTH,
DEXTERITY,
CONSTITUTION,
INTELLIGENCE,
WISDOM,
CHARISMA,
INSPIRATION,
ARMOURCLASS
}
Then I have the corresponding HashMap:
/**
* abilities is a {#link HashMap} collection that contains {#link AbilityScores} as
* keys and {#link Integer} as values.
*/
private HashMap<AbilityScores, Integer> abilities = new HashMap<AbilityScores, Integer>();
And then here is an example of my accessor method for a character's strength:
/**
* This method returns a character's strength in the form of an integer.
* #return strength as an integer.
*/
public int getStrength() {
return abilities.get(AbilityScores.STRENGTH);
}
Am I documenting this correctly or have I incorrectly used '#link' etc. I did find some examples but I wasn't 100% sure as I couldn't find an example (apologies if there is one) where it showed an entire one start to finish like this one.
Any input or guidance is appreciated!
Thank you
What happens if you design a new class and try to insert objects of that class into a HashSet or HashMap without defining a hashCode() method?
Please keep make the explanation easy. I'm studying for an exam and I'm still rusty with hashes in Java. Thank you.
A HashMap stores data into multiple singly linked lists of entries (also called buckets or bins). All the lists are registered in an array of Entry (Entry[] array)
The following picture shows the inner storage of a HashMap instance with an array of nullable entries. Each Entry can link to another Entry to form a linked list.
When a user calls put(K key, V value) or get(Object key), the function computes the index of the bucket in which the Entry should be.
This index of the bucket (linked list) is generated using hashcode of the key.
So, if you have overridden the hashCode method, it will use overridden method to compute index of the bucket
otherwise default hash code is used which is the memory address for your object. So in that case even your objects are you will have a new entry in your map. So even if you try to store logically equal objects. They wil be reataed as different by hash Map.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
For example:
MyObject a = new MyObject("a", 123,"something");
MyObject b = new MyObject("a", 123,"something");
a and b will have different hashcodes.
Nothing will happen :-)
Every object has own hashCode() method that inherited from Object class. So, your every new object will be unique. By herself, they will be identified as unique by HashSet or HashMap.
Here are official comments:
/**
* Returns a hash code value for the object. This method is
* supported for the benefit of hash tables such as those provided by
* {#link java.util.HashMap}.
* <p>
* The general contract of {#code hashCode} is:
* <ul>
* <li>Whenever it is invoked on the same object more than once during
* an execution of a Java application, the {#code hashCode} method
* must consistently return the same integer, provided no information
* used in {#code equals} comparisons on the object is modified.
* This integer need not remain consistent from one execution of an
* application to another execution of the same application.
* <li>If two objects are equal according to the {#code equals(Object)}
* method, then calling the {#code hashCode} method on each of
* the two objects must produce the same integer result.
* <li>It is <em>not</em> required that if two objects are unequal
* according to the {#link java.lang.Object#equals(java.lang.Object)}
* method, then calling the {#code hashCode} method on each of the
* two objects must produce distinct integer results. However, the
* programmer should be aware that producing distinct integer results
* for unequal objects may improve the performance of hash tables.
* </ul>
* <p>
* As much as is reasonably practical, the hashCode method defined by
* class {#code Object} does return distinct integers for distinct
* objects. (This is typically implemented by converting the internal
* address of the object into an integer, but this implementation
* technique is not required by the
* Java™ programming language.)
*
* #return a hash code value for this object.
* #see java.lang.Object#equals(java.lang.Object)
* #see java.lang.System#identityHashCode
*/
public native int hashCode();
I have here a question. Based on Java 7 API Collection is an interface, but yet it comes with some concrete methods, such as size(). I don't get it, how is that interface contains implemented methods. It makes sense if that was an abstract class.
Best regards
Collection is an interface, but yet it comes with some concrete methods, such as size().
This is not true. An interface as you already know just defines the contract and leaves the implementation to classes implementing it. If you're referring to something like
Collection<String> collection = new ArrayList<String>();
System.out.println("Size of the collection is: " + collection.size());
Please note that the size() implementation was provided by the ArrayList not Collection.
java.util.Collection does not have implemented methods, it is an interface. Here's the declaration of the size method:
/**
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* #return the number of elements in this collection
*/
int size();
There is no concrete implementation for any methods. The method you are referring to, size also doesn't have any concrete implementation.
/**
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* #return the number of elements in this collection
*/
int size();
I want that when i mouse over a method i would be able to see my documentation of what the method does like when i put the mouse over Java's method I know that /** */ is how its done but:
How do you explain what the Params Stands for?
How do you create a new line, or make a word bold or italic?
In most major IDEs, such as IntelliJ's IDEA, Apache Netbeans or Eclipse; you can type
/**
and press enter and it will generate the Javadoc for your method, including parameters, return values, etc. You just need to put in the descriptions.
The same applies for class declarations (the Javadoc comment always relates to the following element)
For instance
/**
* create_instance
* #param array of attributes for instance containing web, db, arrival_rate, response_time for instance
* respectively.
* #return Instance object
*/
How do you explain what the Params Stands for?
Use #param tag:
/**
* #param paramName Explanation of the param
*/
public void foo(String paramName);
How do you create a new line, or make a word bold or italic?
Use standard HTML, i.e. <p></p>, <br/>, <strong> and <em> (or less semantic <b> and <i>)