Why doesn't LinkedHashSet implement List? [closed] - java

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
To my understanding, a List is an ordered collection of items. And a Set is a collection of unique items.
Now my question is, why does LinkedHashSet, which describes an ordered collection of unique items, implement the Set interface (=> unique), but not the List interface (=> ordered)?
One possible argument is that List is intended for random access datastructures, but that would be invalidated by the fact that LinkedList doesn't have "true" random access either. In fact, LinkedHashSet is backed by an internal linked list. Also the documentation for List says otherwise:
Note that these [positional index] operations may execute in time proportional to the index value for some implementations.

If it implemented a List you would be able to use it as a List:
List list = new LinkedHashSet();
This might lead to issues with duplicates which don't appear in Set but are allowed in List.
In other words, you shouldn't declare that something is a List when it doesn't allow duplicates even if it holds the order and allows adding, getting, removing and checking the size.
Unlike sets, lists typically allow duplicate elements
--List documentation

because LinkHashSet is class which implements set interface . List and Set has its own functionality List allowed duplicates while set do not allowed duplicates but if you want linear order insertion in a HastSet then LinkedHashSet is used with no duplicates in itself ..
Set s = new LinkedHashSet();
is the implementation of a set in which insertion order is preserved and duplicates do not allowed..

Related

Interview Question - Data structure performing CRUD operation in O(1) time and maintaining insertion order [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 months ago.
Improve this question
Recently I have attended an interview as backend developer, and I've been asked one the following question:
Design a data structure that can perform insert, update, remove, and
contains operation in O(1) time complexity.
It should allay printing all the elements in O(n) time maintaining the insertion order of
elements.
Can someone please explain which data structure we can use and how that data structure allows to achieve the required O(1) time complexity?
It seems like your interviewer was talking about a composite data structure which combines a Linked list and a Hash table.
And JDK offers and implementation of such data structure in the form of LinkedHashMap, which is basically a combination of a HashMap and a LinkedList. It's methods almost as fast as HashMap's ones.
LinkedHashMap capable to perform these operations in amortized O(1) time (only if the Key has a proper hash-function, the worst case would be O(n)):
insertion via put(key, value);
containsKey(key) check;
updating the value of via replace(key, value) and replace(key, oldValue, newValue);
retrieve the values with get(key);
And owing to a LinkedList maintained under the hood is, LinkedHashMap can can track the insertion order of entries (updating the value of an existing entry has no impact on the order).
Here's a quote from the documentation:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

is there a way to have a "main" 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 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.

Java List.add() and Map.put() [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 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)

How to delete particular List object in Java? [closed]

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 list of around 100,000 employees in Java. Now I want to delete a particular employee object from list quickly. What are the possible ways to do it without iterating the whole list?
(If I iterate each object, compare the details then delete: this scenario takes lot of time)
You need a means of find the object quickly. You could
have an ArrayList sorted and then perform a binary search with Collections.binarySearch O(log N) Note: actually removing an element from an ArrayList is O(n) While LinkedList as O(1) for remove, a binary search on it would be pointless i.e. much slower than O(N)
you could have a hash Set of Employee instead and removal would be O(1) amortised. You could use a LinkedHashSet if you would like to preserve some order such as order of insertion.
you could make the object mutable and have a field like enabled which you set to false instead of actually removing it. You could remove it later as a batch job at some time (overnight or on the weekend)
Now I want to delete a particular employee object from list ...
You can just use List.remove to do this
... quickly
In practice, even though removing the item might be an O(1) operation, iterating over the full length of the list is O(n), and is, as you susepcted, not very fast.
I feel that your problem would better be served by the power of a hashmap. This has constant lookup and removal time. The LinkedHashMap class might suit your needs. It maintains insertion order the same way a linked list does, but it also has constant time insertion and deletion.

TreeMap and LinkedHashMap classes [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 7 years ago.
Improve this question
I found a Java question J couldn't understand what should be answer
The TreeMap and LinkedHashMap classes:
enable iteration of a map's entries based on the insertion order of elements only.
enable iteration of a map's entries based on natural ordering of keys only.
enable iteration of a map's entries in a deterministic order.
enable iteration of a map's entries based either natural ordering of keys OR natural ordering of values depending on the arguments sent to the contructor.
In Java:
TreeMap is a Map that automatically sorts the Map entries according to its natural ordering using Comparable<T> interface
LinkedHashMap is Map that guarantees that the entries will be returned in the same order as they were added

Categories