This question already has an answer here:
How to give java enough time to assign a value to a variable? [closed]
(1 answer)
Closed 7 years ago.
I have a HashSet<User> and a User declared outside a while loop, and inside the loop I am setting the name with a setter method and then adding the User to the HashSet with add(User).
This seemed to only update the single User in the HashSet. Only when I declare the User within the while loop is a new User added every time to the HashSet.
I am thinking this is because if the HashSet add() method receives an object with the same memory address as an object currently in the set, it will only update the object and not add another new object to the HashSet. Is this correct?
Then instantiating the User within the loop will cause it to have a different memory address and thus be added to the HashSet as a new object.
I can put code on here, but this is for an assignment and I don't think my professor would like me to share code. The question I have is more about the Java language and not about my assignment, as you can see. If everyone absolutely needs to see code, however, I'll post something useful.
I am thinking this is because if the HashSet add() method receives an object with the same memory address as an object currently in the set, it will only update the object and not add another new object to the HashSet. Is this correct?
That is correct. A HashSet by definition will allow for only one of each unique object. However, the part about updating the object is irrelevant to its membership in the HashSet. Since the HashSet contains only references, any changes you make to the objects (in or out of your while loop) will reflect in the HashSet automatically.
Then instantiating the User within the loop will cause it to have a different memory address
Also true. You'll have different references per object for each instantiation. The HashSet will store one and only one of each.
Related
This question already has answers here:
Collections.emptyList() vs. new instance
(7 answers)
Closed 3 years ago.
I found emptyEnumeration(), emptyIterator(), emptyList() and other methods in Collections class. I searched for examples and purpose but could not found an appropriate one.
It would be a great help if someone can explain with project usability example, wehre emptyList() needs to be created and it is also better to go with it than going with creating a new ArrayList<>() without adding any elements.
They actually return a casted, single instance, so you don't create new objects on the heap for each call to emptyList(). So it's faster and saves memory and GC.
It's an initializer that is used internally by List implementations to decide whether they actually need to allocate space (even adding elements) or keep the list untouched if no elements will be added at runtime (because it happens sometimes, more often than you may think).
Those objects are immutable so you can safely reuse the same instance anywhere, without the synchronization you usually put in place to ensure object status integrity.
The purpose of the empty collection is to be an empty collection! As remarked in a comment, there are times when it is appropriate for a method that returns a collection to be returning an empty collection.
As for why (e.g.) Collections.emptyList() is useful: well, why create your own empty list when you can reuse an existing empty list? It's a minor convenience, a minor saving on memory.
If your code naturally arrives at a point where it (a) knows it needs to return an empty collection, and (b) does not have an empty collection that was created 'naturally', by which I mean something like having created the collection to hold results and then failed to find any such results, then the Collections facilities are handy.
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)
Suppose we have two employee instances having some common attributes like id,name,address (All values are same ).
I want unique objects list without implementing Set.
Please don’t explain the logic with Primitive data type ,I want the uniqueness with Object type.
Simple: you create a "collection" class that calls uses the equals() method of "incoming" objects to compare them against already stored objects.
If that method gives all false - no duplicate, you add to the collection. If true - not unique. No adding.
In other words - you re-invent the wheel and create something that resembles a Java set. Of course, with all the implicit drawbacks - such as repeating implementation bugs that were fixed in the Java set implementations 15 to 20 years ago.
If you don't want to use a Set, use a List. All you need to know to implement uniqueness checking logic is whatequals(Object other) method does:
Indicates whether some other object is "equal to" this one
Now you can test an incoming object against all objects currently on your list, and add it if a match is not found.
Obviously, performance of this method of maintaining a unique collection of objects is grossly inferior to both hash-based and ordering-based sets.
If you cannot use a Set for holding unique instances of your Employee class, you can use a List. This requires you to do two things:
Override equals() (and hashCode()) in Employee to contain the equality logic. This you would need even if you used a Set.
Each time you add items to the list, use List.contains() for checking whether an equal object is already in the list. The method will internally use your Employee.equals() implementation. Add an item only if it's not already in the list. Note that this method is quite inefficient as it needs to iterate through the whole list in worst case (when an item is not already in the list).
I want to make a set of some type of collection (not sure which one yet) as a way of "storing duplicates" in a set. For example if I wanted to add the integer 5 with 39 additional copies I could put it into an arraylist at index 39. Thus if I were to get the size of the arraylist, I would know how many copies of 5 existed within the set.
There are a few other ways I could implement this but I have yet to decide on one. The main issue I'm having with implementing this is that I'm not sure how I can "dynamically" make arraylists (or whatever collection I may end up using) so that whenever someone were to call mySet.add(object), the object is first inserted into a unique arraylist then into the set itself.
Can anyone give me some ideas on how I could approach this?
EDIT:
Sorry I should have been more clear in my question. The point of the code that I'm writing is that we have a set-like collection that allows duplicates. And yes some of the associated methods will be re-written/will have to be re-written. Also my code should be written under the assumption that we do not know what type of object is being inserted(only one data type per set though) nor how many instances of the same object will be added nor how many different unique objects will be added.
I would rather go for using a Map like
HashMap list <Object, Integer>
where Object is the Object that you want to count and Integer is the count
You could try guava's MultiSet, I think it's what you want.
It can store the count of each object. What you need to do is just
multiSet.put(object);
And if it is put for the first time, like you said, a new list will be created, or its count will added by one.
I guess this question that would have already been asked here. I searched but could not find anything similar. So here goes --
I have a custom data object Method and Method is as follows --
public Class Method {
List<String> inputParameters;
String resultVariableName;
}
Now i have a LinkedList<Method> which acts as a repository of Method objects.
Given a Method object is there a way in which the correct index of the Method object can be concretely determined.
My question arises from the face that LinkedList class has an indexOf routine but this routine returns the first occurrence of the object but then there is no given that 2 copies of Method object can not reside in the LinkedList(right ?)
Would tagging every Method object as I add it to the LinkedList solve my purpose and if so is there an ideal way to do it ?
EDIT :
Explaining my use case a little further.
My code basically reads a Velocity template top-down and creates Method objects. One Method object is created for every velocity routine encountered.
This explains why the same element can be stored at multiple indices in the LinkedList as there is no real restriction on how many number of time a Velocity routine is called or the inputs/results provided to the Velocity routine.
Now, i have a UI component, one JButton per Method object reference in the LinkedList<Method> by using which the user can click and edit the Method object.
Thus i need to know which exact Method object reference to edit in the event that same elements reside twice or more number of times in the LinkedList<Method>
What do you mean by the "correct" index in the first place? If the linked list can contain the same element twice or more (and be careful here - the list will only contain a reference to a Method object, not the object itself) then which index would be "correct" in your view?
Of course you can just iterate over the linked list yourself and return all indexes at which a given Method reference occurs, but it's not clear what you're trying to do with it.
Note that indexes aren't often used with linked lists to start with, as obtaining the element at a given index is an O(n) operation.
Duplicates are allowed in LinkedList's.
LinkedList does not avoid duplicates, it may have more than one copy.
You can put a logic to avoid multiple instances, extend the linkedlist class and override the add function to check if Method object already exists.
OR
If you want to get all instances of the Method object, you can use a ListIterator and collect all instances of it, and return this collection as a result.
"there is not given 2 copies of Method object can not reside in the LinkedList", if this is a scenario, how will you identify which object to retrieve??
In this case, I would suggest you to use a LinkedHashMap, where you can use a Identifier as a key to uniquely identify a Method's object.