Java Part of ASSIGNMENT i cant do [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
list() method
// return a string that contains all the HotelRoom objects in the HotelRoom array.
public String list()
{
}
• The list method will return a string containing all the rooms that the user entered into the system. If there are no rooms entered this method lets the user know that no cars exist.
• This method is public, returns a String value and takes no parameters.
• Firstly check that the array is not empty by using the following code:
if(myHotelIn.isEmpty())
{
System.out.println(“All rooms are available”);
}
else
{
In this method the second thing you need to do is to declare a local String variable, called list. This will hold the list of all rooms in the array and will be returned from this method.
• If the HotelRoom array is not empty (hint: use the isEmpty() method),
o write a for loop that will retrieve each room in the array and add its details (room name, room type and room price) to the list variable.
Return the list variable.
}
HEY I HAVE A PROBLEM WITH THIS PART OF JAVA APPLICATION. I HAVE GOT ASSIGNMENT TO DO BUT I AM REALLY STUCK WITH IT, I'VE DONE MOST OF THE WORK BUT THIS ONE GIVE ME A LOT OF TROUBLES. I DON'T KNOW EVEN WHERE TO START. PLEASE IF YOU CAN GIVE ME SOME TIPS WITH IT. THANKS

The first thing you should be looking into is a for each loop. This is a type of loop that goes through every single element in an array or Collection implementation. You can read up on these here.
Next, you'll need to look into the StringBuilder class, which can be read about here. This class is designed to allow efficient creation of a String object, which you will be using.
Finally, you'll need to use the append method in the StringBuilder class, to link up several String representations of each HotelRoom, probably using the toString() method.
NOTE
You'll notice I've not provided any code, because I don't think you've had a fair go at solving the issue just yet. Edit in your attempts and I'll edit in some code.

Related

How can I save only some elements of a List in an ArrayList? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
I tried to do this, but the add in the line arrayList.add give me an error
List <Recipes.Results> list;
ArrayList <Recipes.Results> arrayList;
arrayList = new ArrayList<Recipes.Results>();
for (Recipes.Results re: list){
arrayList.add(re.getId(), re.getTitle(), re.getImage());
}
Im trying to create an arraylist whit only 3 elements of the List, that it contains 5. Example, the List contain a class Results whit id, image, title, nutrients, typeimage. I want only to pass id,image and title to the arraylist. How can I do that?
The add method requires a Recipes.Results object as a parameter. You are passing in a set of member variables instead. Before the call to the add method, put in some condition or processing to determine what object to add to the ArrayList. You mat need to define a new class that is similar to Recipes.Results that contains just a subset of the data, or you may wish to construct new Recipes.Results objects that contain 1 or more null fields.

Collections.emptySet() vs new HashSet<>() [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How can I validate if the Set is empty set or new HashSet<>() ?
Tried two approaches -
size
CollectionUtils.isEmpty()
Both result in same value.
Of course, a fresh new HashSet<>() is empty, and so is Set.of() or Collections.emptySet(). The point is: Both are empty sets, I have no idea why you would want to tell the difference between these two.
The one difference is that new HashSet<>() is empty now but may not be empty later (it can be changed; you can add things to it), whereas as per the spec, the result of Set.of() or Collections.emptySet(), they are empty now and will be empty later: You can't add anything to them, calling .add on them will cause a runtime exception.
That's tantamount to asking: How do I know if it is immutable. You unfortunately basically can't, so that goes right back to: Why would you need to know?
Collections.emptySet() returns a static class EmptySetwithin java.util.Collections but new HashSet<>() returns a java.util.HashSet class. Both collections will be empty, i.e., size = 0 after instantiated but you can distinguish those two by calling .getClass() which will return:
class java.util.Collections$EmptySet
class java.util.HashSet
Use .getClass to see the different implementation that was used.
I got one utility method that can be used to perform the operation -
Collections.EMPTY_SET.equals(mySet)
Thanks all for your answers.

Why does Java not implement a last() method for ArrayLists? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am not asking how to find it, that is already answered in this other question:
But just going deeper into data-structures in Java, I have found out that the LinkedList implementation has a getLast() method that is not implemented (I suppose for some reason) in the ArrayList implementation. I could not find any other similar question nor post on Internet explaining it, so I decided to ask it here.
We may agree that it is not elegant the current way of getting the last element from an ArrayList, and usually this implementation is more widely used than LinkedList because it performs better in a wider range of scenarios, as discussed here.
Does anybody know why ArrayList does not implement that method?
Edit: I have edited my question to avoid confusion and opinion based answers. The answer below from Andreas is the one I was looking for, based on facts and references.
The Collection classes generally don't implement any public methods that aren't specified by an interface.
ArrayList does have one method named trimToSize() that isn't specified by an interface, but that is a very implementation-specific method.
LinkedList doesn't have any methods that isn't specified by an interface.
The reason LinkedList has a getLast() is shown in the javadoc:
Specified by:
getLast in interface Deque<E>
Deque has most of the same methods as List does. The main difference is that List has methods for accessing elements by index position, while Deque has methods for accessing first / last element.
If you want to work with a list-like collection structure where access to the last element is simple, code to the Deque interface, not the List interface, and use ArrayDeque instead of ArrayList.
You can access an ArrayList last element with a simple ArrayListName.get(ArrayListName.size() - 1); because you can access an ArrayList element directly with it's index, however in a linked list you have to iterate through every element before you're able to access the last element, this is [most probably] why the engineers created a method to access the last element of a linked list.

ArrayList<String> objects point to null. Why? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a piece of code that takes in an ArrayList<String> object and eventually takes that object and adds it to a HashMap object as the key. When I print the hashmap, the key's are all null while the values are correct.
I already know I can fix the code by passing in a copy of the ArrayList<String> object and that fixes my issue (i.e. buildHash(new ArrayList<String>(key)). But why does it point to null otherwise?
HashMap<ArrayList<String>, ArrayList<String>> hash = new HashMap<>();
ArrayList<String> key = new ArrayList<String>();
for (int i = 0; i <= 9999999; i++) {
key.add(//different strings depending on the iteration);
if ( !hash.contains(key) ) {
buildHash(key);
}
key.clear();
}
private void buildHash(ArrayList<String> key) {
ArrayList<String> follows = new ArrayList<String>();
for (int index = 0; index <= 9999999; index++) {
// add stuff to follows...
}
hash.put(key, follows);
}
I thought that the value of the key would be added to the hash, and the hash's keys would point to the value it was before it was cleared by key.clear(). That way I could reuse key over and over without creating another object in memory.
I'm new to Java (and coding) so I'm probably naive, but I thought I could save memory by utilizing the mutability of ArrayLists as opposed to Lists as the number of operations and key's generated for this project are well into the millions, if not more. Is there no avoiding that? And if not, is there any other optimization I could do?
As documented, ArrayList::clear removes all elements from the list. So you are wiping out the content.
utilizing the mutability of ArrayLists
Exactly what you do not want in a key. An object used as a key in a map should never be modifiable, not in a way that affects the outcome of the hash value calculation or affects the outcome of the equals method. Would you expect to find someone in a phone book after they changed their name?
It hard for me to imagine where you would ever want to use a list as a key in a map.
As for trying to “save memory”… don’t. The last thing a new programmer should worry about is conserving RAM. Write simple code, easy to read, easy to edit. Then let the JVM do the optimizing work for you.
I suggest you not try so hard at being clever. Spend some time looking at other code. Search Stack Overflow and elsewhere to find code similar to your logic problem or the classes you are using. Then study code samples.

Is it a bad practice to change the value of an object, bypassing the setter? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
That is, I get the object through the get-method. And then change the value. Thus, I do not create a copy of this object, but change the value of the original.
Example with List:
getMyListFromPojo().addAll(additionalList);
This code will change the value in the field myListFromPojo! Is this a normal practice?
Is it a bad practice to change the value of an object, bypassing the setter?
A good API won't allow you to change the value. getMyListFromPojo() would return an unmodifiable collection, no one from the outside would be able to alter the value returned.
On the other hand, a POJO class is supposed to be a very simple class. I rarely see POJO methods return something more complex (for instance, a copy or an immutable object) than a reference to a corresponding field.
It depends on what you want to achieve with your object, if you need your object to be immutable(except by using some methods provided), then you would need to show a copy of that object(or make it immutable by using methods like Collections.Immutable).
To answer your question: it's perfectly fine to modify a list returned by a method(if that is what you want).
I would instead write two methods:
one for adding a single object to the list
public void addToListFromPojo(Object object) {
this.myListFromPojo.add(object);
}
and another one for adding a list of objects to it
public void addAllToListOfPojo(List<Object> objectList) {
this.myListFromPojo.addAll(objectList);
}
That would result in more (theoretically unnecessary) code, but it would support readability and
keep the responsibility of changing the fields inside the class.
If you don't care for responsibilities of units of your code, then just use less code ==> your example
This code will change the value in the field myListFromPojo! Is this a normal practice?
It is your code, thus your decision.
If you want to allow for such things, nicely document that in JavaDoc, and ensure that the underlying List is an ArrayList for example that allows any kind of modification.
If, on the other hand, you do not want such changes to take place, then nicely document that in JavaDoc, to then ensure that your APIs do not allow for it to happen. For example by making sure that the List instance is actually some sort of ImmutableList.
And note that both ways can be legit. It is really up to the person defining the APIs here what is acceptable and what not. Of course, the first premise would be that all things in your API behave in the same way.
Beyond that, such DTOs/Beans are typically meant to only contain values, so updating them is often allowed. But of course, it can lead to problems when multiple threads come into play. From a consistency point of view, you are always better off to forbid modifications (instead: changes create new objects with new content). But sometimes the performance penalty for doing that might be considered too high.

Categories

Resources