Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Just wondering if there is a better approach to building to the web app that I'm creating? I'm not going to show a lot of code, I'm more interested in following best practices:
Index.html contains a static form
User fills out the form and the POST request is handled by a Java Servlet
The servlet contains 3 methods:
doPost(HttpRequest,
HttpResponse)
doGet(HttpRequest, HttpResponse)
processRequest(Map map)
doPost() constructs a hashmap and assigns all of the variables from the form to it in key:value format. Then it calls the method processRequest(Map map)
processRequest(Map map) has one function: to create a new instance of class formParser with the map variable: i.e. formParser parser = new formParser(map);
The class formParser has a constructor and a method:
the constructor initializes a new HashMap which clones the original and a new LinkedList which is to store the values and calls the method with the map parameter
Map<String, String> paramMap = new HashMap<String, String>(map);
List<String> paramList = getParams(paramMap);
The method public LinkedList<String> getParams(Map paramMap) then checks all of the key:value pairs in the map and only takes those that have no null values
I then use the valid key:value pairs to write certain XML snippets to a pre-existing XML skeleton, which is sent to an external REST-API. I have yet to write this code.
EDIT: I should add that I'm new to Java Web programming, and this is why I'm only trying to validate the efficacy of my approach to the program, rather than the code itself. That will come later.
I think that step 6 can be improved a little by not creating the LinkedList. If I understand correctly the LinkedList is used to remove NULL values. This can be achieved by iterating over the keys of the map, retrieving their value and removing any keys from the map that have NULL values.
Map map = new HashMap<String, String>();
map.put("name1","somevalue");
map.put("name2",null);
for(String s : map.keySet()){
String value = map.get(s);
if ( s == null){
map.remove(s);
}
}
I don't know what you exactly mean by "efficiency", but if you are talking about performance, I don't see anything crazy being done in the steps you describe, and IMO that's enough.
Go with the simplest, most usual design and you can improve performance if there is a problem. In my experience, 99.999% of performance problems in web apps come from doing crazy stuff (i.e. unusual, complex approaches).
Since you are new to web programming you should not consider performance problems.
Just focus on working code.
Related
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 4 months ago.
Improve this question
Why is the following code a bad practice and what is the solution for it?
TreeSet<Map.Entry<Integer, Map<String, String>>> sortedtable = new TreeSet<>(new ComparatorByDueDate());
public void sortTable(Map<Integer, Map<String, String>> table){
sortedtable.addAll(table.entrySet());
}
Update: As per Sonar, it is a bad practice. I am asking the question here as the sonar explanation seems confusing.
Java Map.Entry objects are not intended for long term storage. From the docs (emphasis mine),
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
If anyone, for any reason, adds, removes, or modifies any part of the map after the fact, then your TreeSet entries now have undefined behavior. They might still be good, they might get nulled out, they might exhibit some random behavior.
If you want to store a pair of elements, then write a class that has two instance variables. If you're on a new enough Java version, then records are great for this sort of thing.
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
Let's say I have
ArrayList<Citizen> citizen1 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen2 = new ArrayList<Citizen>();
ArrayList<Citizen> citizen3 = new ArrayList<Citizen>();
is it possible to have an arraylist which compromise them all?
List<List<Citizen>> mainList= new ArrayList<>();
You can go with List of List.
Also need to consider below points.
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
You can have a List of Lists of Citizen, like this: List<List<Citizen>>= new ArrayList<>();
You can use the addAll() methods of List and Collection to add to one List all the elements of another list.
If using at least Java 8, you can do various things using the Streams API: Stream.of(), Stream.concat(), and maybe others.
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 5 years ago.
Improve this question
Working with Lists and Maps, I started thinking, why Map method for adding Object is called put and for List it is add?
It is just developers will, or there was something under naming those methods different.
May be the methods names let the developer know while adding to Map/List what kind of data structure he is working with?
Or those names describes the way they works?
The difference is :
.add() means to insert something at the end or wherever you want to(you know where to add) whereas
.put() means to add an element wherever it needs to be placed, not necessarily at the end of the Map, because it all depends on the Key to be inserted (you don't know where to add).
To me, it has some cause.
After all, List is a dynamic array, which internally consists a logical index where we are adding.
And map internally carry a bucket of key and value pair. So kind of we are putting something into the bucket.
It can be stated as so because to get a clear understanding.
As java is a 3rd level human understandable language this also can state as a simple English for better understanding.
Collection#add() can be seen that you add your value to a pool of something (an implementation of Collection<E> defines what pool actually is).
Whereas with Map#put() you associate your value with the key which potentially already had a value associated with it.
Add will always add an entry to the end of a list.
Put injects an entry into the map if the key does not already exist; if the key already exists, the value is updated.
Thus the operations are different. On some level, the authors of the API have to make decisions that balance out various concerns. Add to a set has some aspects of add to a list and put to a map, in that adding an "equal" entry has no effect.
For this you should just read the Java docs for add and put.
They are 2 different function, that take completely incompatible inputs, and return completely incompatible values. They are 2 completely separate and distinct functions that behave completely differently (other than they both are for adding elements to a collection (the concept, not interface. As map doesn't implement that interface)).
From the docs
PUT
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
ADD
Appends the specified element to the end of this list (optional operation).
Lists that support this operation may place limitations on what elements may be added to this list. In particular, some lists will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. List classes should clearly specify in their documentation any restrictions on what elements may be added.
List :- If i say i'm adding some items to the some Container ill say that i have added the items to the container.Here we are more concentrate on the new item Addition to the existing container or List (in java).
Map :- If i want to put some of the things to the some locker or my computer which is already having the things which i dont care about i just have to put not add.
Here we are concentrate to addition of new data to the locker or Map (in java) regardless of existing the thing.
Real time example:- you add sugar to the tea keeping in mind the amount which is already their.you put your cloths to the Clothing Store regarding their exist any cloths or not.
In java side :-
if you list is like this :-
List<String> list = new ArrayList<String>();
list.add("java");
list.add("php");
list.add("python");
list.add("perl");
list.add("c");
list.add("lisp");
list.add("c#");
and you want to add something to the list you have to care about the existing thing because if it is list it will add duplicate and if set then don't duplicate.
If you create a Map.
Map<String, Object> foodData = new HashMap<String, Object>();
foodData.put("penguin", 1);
foodData.put("flamingo", 2);
and again you are adding something foodData.put("penguin", 3); you don't have to worry about adding and update the data internally.
I think if you get into etymology we can only guess that since when you place a value into a list you always increase the list length, however if you put the value into a map you would not necessary increase the number of map entries (if the key already exists)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a HashSet which contains the keys of a HashMap, and update the contents of the HashMap, adding a new key in the process. After I've done this, I then want to use the HashSet of keys again, since I know that they kept up to date with the keys of the HashMap. I just want to make sure that this is all done by the same thread, and that there is no concurrency going on here that I might be unaware of, such that I tell the HashMap to add the new entry, and before it has updated I have used the HashSet information while it is out of date.
In code:
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
HashSet<String> myHashSet = myHashMap.keySet();
... processing ...
myHashMap.put(new_key, value);
... use the **original** HashSet of keys, myHashSet ...
Could the above situation occur, given that this is the only thread created by the programmer, such that myHashMap and myHashSet would be out of sync? I'm not talking about the programmer creating more than one thread - the main program runs in a single thread (see above).
No they won't because the key set is a view onto the actual keys in the HashMap.
From the Javadocs:
The set is backed by the map, so changes to the map are reflected in
the set, and vice-versa.
And you can see the same in OpenJDK's implementation of HashMap.
So for a single-threaded program these should always be in sync.
The Java collections classes don't do things with threads internally because it would make using them too difficult and error prone. They leave the threading model to the calling code and just provide guarantees (or otherwise) about which operations are thread-safe.
This question already has answers here:
Type List vs type ArrayList in Java [duplicate]
(15 answers)
Closed 9 years ago.
What's the difference between the following two declaration statements:
HashMap<Character, Character> map = new HashMap<Character, Character>();
Map<Character, Character> map = new HashMap<Character, Character>();
Any advantages of using the interface Map instead of HashMap in this particular case?
In the following case, is Map definitely better because the method can accept different types of maps?(if it is intended to)
public void method(Map map){
}
There is no underlying difference. It is more about the interface. There's an advantage of using a Map though, that is you can change the object to be a different kind of a Map without breaking the contract of the code using it.
The HashMap is an implementation of Map, which is part of the Java Collections Framework. If you settle on using the HashMap and then the other party wishes for something different, like LinkedHashMap (preserves iteration order), then you have to change things around. Here's a diagram (courtesy ProgramCreek).
There are other things like computational time complexity, if you care about performance. Here's a small table that helps. Choosing the right thing is a question of design and need i.e. what are you trying to do. It varies from project to project.
The second version is preferred because if you want to write code later to change map to a different kind of Map, you will need to use the second version. But it really is a matter of personal preference.
in the perspective of the object-oriented,During compilation,
the method is bound reference class type,
so HashMap map = new HashMap();
You can us hashMap methods ,Including the realization map and extended. But ,
Map map = new HashMap();
You can only use methods declared in map .Can not used hashMap methods.