Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
Improve this question
what is the main difference with org.apache.myfaces.trinidad.util.ArrayMap and java.util.HashMap?
Is ArrayMap is thread safe?
In the documentation it is mentioned that Array is best in performance wise.
I don't want to use hashmap or concurrent hashmap. I want to try other like below. which one is best alternative If I consider Thread safety and performance?
ArrayMap<String,String> var= new ArrayMap<String,String>();
HashMap uses an array underneath so it can never be faster than using an array correctly.
Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.The reason your array is so slow is due to the equals comparisons, not the array access itself.
An ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.
List:
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.
Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
The list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background. You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarantee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).
When to use Arrays?
Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.
Sometimes, it may be best to use a combination of the above approaches. For example, you could use a ArrayList of HashMap to suit a particular need.
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 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)
A HashSet is backed by a HashMap. From it's JavaDoc:
This class implements the Set interface, backed by a hash table
(actually a HashMap instance)
When taking a look at the source we can also see how they relate to each other:
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
Therefore a HashSet<E> is backed by a HashMap<E,Object>. For all HashSets in our application we have one reference object PRESENT that we use in the HashMap for the value. While the memory needed to store PRESENT is neglectable, we still store a reference to it for each value in the map.
Would it not be more efficient to use null instead of PRESENT? A further consideration then is should we forgo the HashSet altogether and directly use a HashMap, given the circumstance permits the use of a Map instead of a Set.
My basic problem that triggered these thoughts is the following situation: I have a collection of objects on with the following properties:
big collection of objects > 30'000
Insertion order is not relevant
Efficient check if an item is contained
Adding new items to the collection is not relevant
The chosen solution should perform optimal in the context to the above criteria as well as minimize memory consumption. On this basis the datastructures HashSet and HashMap spring to mind. When thinking about alternative approaches, the key question is:
How to check containement efficiently?
The only answer that comes to my mind is using the items hash to calculate the storage location. I might be missing something here. Are there any other approaches?
I had a look at various issues, that did shed some light on the issue, but not quietly answered my question:
Java : HashSet vs. HashMap
clarifying facts behind Java's implementation of HashSet/HashMap
Java HashSet vs HashMap
I am not looking for suggestions of any alternative libraries or framework to address this, but I want to understand if there is an other way to think about efficient containement checking of an element in a Collection.
In short, yes you should use HashSet. It might not be the most possibly efficient Set implementation, but that hardly ever matters, unless you are working with huge amounts of data.
In that case, I would suggest using specialized libraries. EnumMaps if you can use enums, primitive maps like Trove if your data is mostly primitives, a bunch of other data-structures that are optimized for certain data-types, or even an in-memory-database.
Don't get me wrong, I'm someone who likes performance-tuning, too, but replacing the built-in data-structures should only be done when its really necessary. For most cases, they work perfectly fine.
What you could do, in case you really want to save the last bit of memory and do not care about inserting, is using a fixed-sized array, sorting that and doing a binary search every time. But I doubt that it's more efficient than a HashSet.
Hashtables and HashSets should be used entirely different, so maybe the two shouldn't be compared as "which is more efficient". The hashset would be more suitable for the mathematical "set" (ex. {1,2,3,4}). They contain no duplicates and allow for only one null value. While a hashmap is more of a key-> pair value system. They allow multiple null values as well as duplicates, just not duplicate key vales. I know this is probably answering "difference between a hashtable and hashset" but I think my point is they really can't be compared.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Rule of thumb for choosing an implementation of a Java Collection?
My situation is this:
I have a collection of objects that I need to hold and every now and then iterate through
The size of the collection is dynamic
The iteration should access each element
The collection does not need to be sorted
Creating or updating the collection has no time constraints but I'd like to iterate through the collection as fast as possible.
What would be the best Collection to use (or would you perhaps suggest using an array?)
You can use a List collection probaly ArrayList.
It depends on the parameters like whether it is an ordered collection, whether you want to maintain the insertion order, whether you want to maintain uniqueness etc
List vs Set
Set: Unique, unordered collection
List: ordered collection, allows duplicate elements
ArrayList vs LinkedList
In general : If you don't have particular constraints, an ArrayList is you best bet. Unless you have extremely tight performance control, don't go for a blank array, you have too much chance for errors (and a big chance of not outperforming the ArrayList implementation).
In your case the fast iteration requirements means ArrayList is a good choice.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a List vs. an ArrayList?
Ive used both of them, but im just wondering what are the pros and cons between them? What are the major differences? And which one is better to use?
Thanks.
List is an interface implemented by ArrayList class. Another well-known implementation of the List is LinkedList.
ArrayList provides constant-time random access, while LinkedList provides constant time for non-sequential access. When you declare a variable that will hold an ArrayList, consider accessing it through an interface, like this:
List<ElementType> myList = new ArrayList<ElementType>();
This will let you swap in a different implementation without disturbing the rest of your code.
List merely describes the contract of what it means to be a list. As such, it is not a concrete implementation but merely an interface. A list can be implemented in a number of ways.
In particular, you have ArrayList, which internally keeps a dynamic array for storing all the elements in order. You also have LinkedList, which stores elements as a doubly linked list i.e. a sequence of nodes which keep references to the previous and next nodes.
Vector is another List, much like an ArrayList in that its implementation is based on a dynamic array; it's, however, a relic of the older versions of Java and is guaranteed to be thread-safe by being wholly synchronized. In practice, new Vector<T>() is more-or-less equivalent to Collections.synchronizedList(new ArrayList<T>()).
The reason for having a List is that a list can come implemented in a number of ways. That being said, often you want to have some sort of generic behavior that can be applicable to all Lists... see polymorphism.
A List is an interface, and an ArrayList is an implementation of that interface. An ArrayList is a List, and so are LinkedLists, Stacks, Vectors, etc.
the other posters already answered the "what" part of your question. Some considerations to think about when choosing between them.
An ArrayList uses an array behind the scenes. So accessing by index can be done in constant time. Adding can also be done in constant time, if the array has been allocated with enough space. However, when the space runs out, ArrayList will allocate a larger array and copy the old array values into the new one.
A LinkedList uses nodes that are chained together. Accessing by an index can potentially require walking the entire list (linear time). Inserting only requires creating a new node and adding it at the end (which could be constant time if a tail pointer is maintained).
So "which one is better" can depend on how you are using it. Truthfully, I've never measured performance differences between the two, but it's just something to consider.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I believe Array and ArrayList both are non-Synchronised;behave same in multiThreaded env.
And both are Index based. Only Adavantage is ArrayList has utility methods and flexible.
Apart from those Utility methods only to get and set fixed no of Objects which is best in java? Is there any overhead in using Arraylist than Array? Pls explain.
Let us consider Scenario like
1) 1,00,000 Objects to be stored.
2) 1,00,000 primitives to be stored
To be able to answer question on which data representation fits better, one needs to know many details like:
how many elements will be stored in the structure?
will the structure be mutable or immutable, that is, will the contents of the it change after initialization?
do you know the final size of your structure when you initialize it?
how will you access the elements? iterate over it? random access by index?
etc.
Regarding the array vs. arraylist: arraylist performance overhead is minimal and in most cases it is not significant. On the other hand, it is more flexible. see this thread Array or List in Java. Which is faster?
ArrayLists will have an ever so slightly higher overhead than an array. This is because an ArrayList is just a wrapper for an array with a few convenience methods added. Though if you know exactly how many elements you will ever have then ArrayList doesn't add much.
The biggest advantage of having an array over an ArrayList (at least in Java), is the cleaner syntax. eg.
myArray[0] = x;
// as opposed to
myList.set(0, x);
// personally I can never remember the order for the arguments and I have to check
Adding all the elements to another list
One possible advantage to ArrayLists is being able to easily add all the elements in an ArrayList to another list.
anotherList.addAll(myList);
However, the same can easily be accomplished by using the Collections util class.
Collections.addAll(anotherList, myArray);
Immutability
One problem is that arrays are mutable (element values can be changed), but you may only want to present a immutable view of your collection of elements to classes outside your own class. Here lists can be useful again.
List<E> readOnly = Collections.unmodifiableList(myList);
But in this case also Arrays can still easily be used to to back an immutable list.
List<E> readOnly = Collections.unmodifiableList(Arrays.toList(myArray));
Synchronized access
Finally, and most importantly, you can make use of the Collections class to make your Lists synchronized.
List<E> syncedList = Collections.synchronizedList(myList);
You could wrap your array in a list and make access synchronized, but then you'd still have to use access via the list, so there wouldn't be much point in having an array.
Final word - Personal preferences
In general though, the whole thing comes down to preference. What is your personal preference, do you prefer working with arrays or Lists? Personally I prefer lists because they work better with the rest of the collections API and making a generic Lists is easy, making generic arrays is a real pain.
List<E> list = new ArrayList<E>(); // easy
E[] array = new E[]; // compilation error
A ArrayList uses internally an Array. So yes, an ArrayList has a little bit of overhead, but it provides you with some convienent methods to access the elements in the list. It depends what you prefer.
If count of Objects is fixed, obviously Array is better solution. Because ArrayList uses array which can be created several times during adding.As javadoc says in array list function
Each ArrayList instance has a capacity. The capacity is the size of
the array used to store the elements in the list. It is always at
least as large as the list size. As elements are added to an
ArrayList, its capacity grows automatically.