What is the Difference Between addItem and inserItemAt method in java?
One thing that i have noticed while making a program is that addItem method starts putting
entries in the last in JComboBox.
insertItemAt method pins the entry at specific position.
*Is That The Only Difference? *
It depends on the implementation of the underlying datamodel but as for the semantics, yes that would be the only difference. Here are some differences for insertItemAt:
- might throw an IndexOutOfBoundsException if the specified index is invalid
- does not select an item whereas addItem selects the inserted item if it is the only one in the list
Different implementation might do things differently and have different performance, e.g. a linked list might be faster for insertItemAt than an array based list.
Is That The Only Difference?
From the standpoint of how it affects the underlying Collection, yes.
Both insert items, the only diference is: the first insert the item in the end like a stack, and the second one inserts an item in an indicated position, obviously moving the items according to.
So basically, yes, that's the only differece
Related
In Java a view is a lightweight object which implements the Collection or Map interface but is not a real collection. When we use Map.values() in Java we get a view of the values stored against keys in a Map interface. Like other collections in Java a view also comes with get() and set() methods. I cannot find any hint to access the first or last value in a view. The get() method accepts a perimeter and searches for that perimeter and on finding that passed value it returns that. So is there a way through which one can get the first value of a Java view.
I tried to using get() method but I know that it doesn't looks at particular index it rather searches for the provided value in the collection.
tl;dr treat views like any other collection, there's nothing special about them being views. For some of them you can get the first/last. For others you can't. For all of them you can "fake" it by using iteration order (which may or may not be meaningful).
Whether or not a given view even has the concept of a first or last object depends on what it represents. A few representative examples are as follows:
Map.keySet() returns a Set because the order of keys in a Map is undefined and there can't be any duplicates
Map.values() returns a Collection because the order of its values is undefined. It can also contain duplicates, so it can't be a Set.
List.sublist() returns a List because it's simply a "zoomed in" view of a List so getting the first/last works just like any other.
SortedSet.subSet() returns another SortedSet for reasons analogous to the List.
When the view happens to be a List then l.get(0) and l.get(l.size()-1) will return the first/last element respectively.
If the view is a Collection then there is no meaningful "first" or "last", because there's no defined order. You could use iterator() and designate the first value returned by next() as the "first" and the last one as "last", but that depends on the iteration order which is frequently undefined (plus iterating to the last element could be quite expensive).
If the underlying object is a Collection then there is no order: in Java, a Collection has no ordering, and so there is no concept of a first or last element.
You could sort the collection and then retrieve the first value instead.
I have had this question for a while but I have been unsatisfied with the answers because the distinctions appear to be arbitrary and more like conventional wisdom that is sort of blindly accepted rather than assessed critically.
In an ArrayList it is said that insertion cost (for a single element) is linear. If we are inserting at index p for 0 <= p < n where n is the size of the list, then the remaining n-p elements are shifted over first before the new element is copied into position p.
In a LinkedList, it is said that insertion cost (for a single element) is constant. For instance if we already have a node and we want to insert after it, we rearrange some pointers and it's done quickly. But getting this node in the first place, I don't see how it can be done other than a linear search first (assuming it isn't a trivial case like prepending at the start of the list or appending at the end).
And yet in the case of the LinkedList, we don't count that initial search time. To me this is confusing because it's sort of like saying "The ice cream is free... after you pay for it." It's like, well, of course it is... but that sort of skips the hard part of paying for it. Of course inserting in a LinkedList is going to be constant time if you already have the node you want, but getting that node in the first place may take some extra time! I could easily say that inserting in an ArrayList is constant time... after I move the remaining n-p elements.
So I don't understand why this distinction is made for one but not the other. You could argue that insertion is considered constant for LinkedLists because of the cases where you insert at the front or back where linear time operations are not required, whereas in an ArrayList, insertion requires copying of the suffix array after position p, but I could easily counter that by saying if we insert at the back of an ArrayList, it is amortized constant time and doesn't require extra copying in most cases unless we reach capacity.
In other words we separate the linear stuff from the constant stuff for LinkedList, but we don't separate them for the ArrayList, even though in both cases, the linear operations may not be invoked or not invoked.
So why do we consider them separate for LinkedList and not for ArrayList? Or are they only being defined here in the context where LinkedList is overwhelmingly used for head/tail appends and prepends as opposed to elements in the middle?
This is basically a limitation of the Java interface for List and LinkedList, rather than a fundamental limitation of linked lists. That is, in Java there is no convenient concept of "a pointer to a list node".
Every type of list has a few different concepts loosely associated with the idea of pointing to a particular item:
The idea of a "reference" to a specific item in a list
The integer position of an item in the list
The value of a item that may be in the list (possibly multiple times)
The most general concept is the first one, and is usually encapsulated in the idea of an iterator. As it happens, the simple way to implement an iterator for an array backed list is simply to wrap an integer which refers to the position of the item in a list. So for array lists only, the first and second ways of referring to items are pretty tightly bound.
For other list types, however, and even for most other container types (trees, hashes, etc) that is not the case. The generic reference to an item is usually something like a pointer to the wrapper structure around one item (e.g., HashMap.Entry or LinkedList.Entry). For these structures the idea of accessing the nth element isn't necessary natural or even possible (e.g., unordered collections like sets and many hash maps).
Perhaps unfortunately, Java made the idea of getting an item by its index a first-class operation. Many of the operations directly on List objects are implemented in terms of list indexes: remove(int index), add(int index, ...), get(int index), etc. So it's kind of natural to think of those operations as being the fundamental ones.
For LinkedList though it's more fundamental to use a pointer to a node to refer to an object. Rather than passing around a list index, you'd pass around the pointer. After inserting an element, you'd get a pointer to the element.
In C++ this concept is embodied in the concept of the iterator, which is the first class way to refer to items in collections, including lists. So does such a "pointer" exist in Java? It sure does - it's the Iterator object! Usually you think of an Iterator as being for iteration, but you can also think of it as pointing to a particular object.
So the key observation is: given an pointer (iterator) to an object, you can remove and add from linked lists in constant time, but from an array-like list this takes linear time in general. There is no inherent need to search for an object before deleting it: there are plenty of scenarios where you can maintain or take as input such a reference, or where you are processing the entire list, and here the constant time deletion of linked lists does change the algorithmic complexity.
Of course, if you need to do something like delete the first entry containing the value "foo" that implies both a search and a delete operation. Both array-based and linked lists taken O(n) for search, so they don't vary here - but you can meaningfully separate the search and delete operations.
So you could, in principle, pass around Iterator objects rather than list indexes or object values - at least if your use case supports it. However, at the top I said that "Java has no convenient notion of a pointer to a list node". Why?
Well because actually using Iterator is actually very inconvenient. First of all, it's tough to get an Iterator to an object in the first place: for example, and unlike C++, the add() methods don't return an Iterator - so to get a pointer to the item you just added, you need to go ahead and iterate over the list or use the listIterator(int index) call, which is inherently inefficient for linked lists. Many methods (e.g., subList()) support only a version that takes indexes, but not Iterators - even when such a method could be efficiently supported.
Add to that the restrictions around iterator invalidation when the list is modified, and they actually become pretty useless for referring to elements except in immutable lists.
So Java's support of pointers to list elements is pretty half-hearted an so it's tough to leverage the constant time operations that linked list offers, except in cases such as adding to the front of a list, or deleting items during iteration.
It's not limited to lists, either - the ConcurrentQueue is also a linked structure which supports constant time deletes, but you can't reliably use that ability from Java.
If you're using a LinkedList, chances are you're not going to use it for a random access insert. LinkedList offers constant time for push (insert at the beginning) or add (because it has a ref to the final element IIRC). You are correct in your suspicion that an insert into a random index (e.g. insert sorted) will take linear time - not constant.
ArrayList, by contrast, is worst case linear. Most of the time it simply does an arraycopy to shift the indices (which is a low-level shift that is constant time). Only when you need to resize the backing array will it take linear time.
I am implementing a public method that needs a data structure that needs to be able to handle insertion at two ends. Since ArrayList.add(0,key) will take O(N) time, I decide to use a LinkedList instead - the add and addFirst methods should both take O(1) time.
However, in order to work with existing API, my method needs to return an ArrayList.
So I have two approaches:
(1) use LinkedList,
do all the addition of N elements where N/2 will be added to the front and N/2 will be added to the end.
Then convert this LinkedList to ArrayList by calling the ArrayList constructor:
return new ArrayList<key>(myLinkedList);
(2) use ArrayList and call ArrayList.add(key) to add N/2 elements to the back and call ArrayList.add(0,key) to add N/2 elements to the front. Return this ArrayList.
Can anyone comment on which option is more optimized in terms of time complexity? I am not sure how Java implements the constructor of ArrayList - which is the key factor that decides which option is better.
thanks.
The first method iterates across the list:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
which, you can reasonably infer, uses the iterator interface.
The second method will shift elements every time you add to the front (and resize every once in a while):
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#add(int, E)
Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Given the official assumptions regarding the functions, the first method is more efficient.
FYI: you may get more mileage using LinkedList.toArray
I would suggest that you use an ArrayDeque which is faster than a LinkedList to insert elements at two ends and consumes less memory. Then convert it to an ArrayList using method #1.
Eg.:
{2,3},{1,2},(2,2},{3,1},{2,1} to {1,2},{2,1},{2,2},{2,3},{3,1}
Here's what I'm thinking:
Do a merge sort on the first column of values. Iterate over the set to see if there are any duplicate values in the first column. If there are, enqueue them onto a list.
Merge sort this list on the second column and then integrate them into the main set. While it does seem feasible to do, it seems overly complicated. This should run in O(NlogN), so if somebody can think of a faster/same complexity algorithm that's also simpler, please post it!
Thanks!
Simply implement a Comparator<T> which compares any two objects of your type by first comparing the first field, and then moving on to the second field if the first fields are equal. You can then copy the set into a list, call Collections.sort and give it the list and your comparator. There's no need to implement sorting yourself.
The comparator would be something like:
public class TwoFieldComparator implements Comparator<Foo>
{
public int compare(Foo first, Foo second)
{
// TODO: null checks
int firstComparison = Integer.compare(first.x, second.x);
return firstComparison != 0 ? firstComparison
: Integer.compare(first.y, second.y);
}
}
Alternatively, you could make your class implement Comparable<T> in the same sort of way.
What you have to do is performing a stable sort on the second column then once more on the first column.
If the range of the numbers can be determined, O(N) can be achieved with some linear sort.
EDIT:
Take 'merge sort' as an example(for it's stable):
1, Run a merge sort on the second column, then number pairs will be arranged according to the value of second column.
2, Run a merge sort again on the first column, number pairs will be arranged in the order of first column value. However, because the sorting method is stable, that means if the first number is the same, the second number will be sorted as well(we did it in the first sort).
Thus, the num pair array is in order now. No more action is needed.
Merge sort is O(NlogN), thus 2*O(NlogN) is still O(NlogN).
EDIT2:
Well, I might make this problem complicated. Even if the sorting method is needed to be implemented by our own, as long as the data stucture has been determined, filling the compare code by Jon Skeet in the corresponding part of the hand-make sorting method will be the most convenient way.
As you mentioned in one of your commments, this is interview question. Solution by John Skeet shows that you don't have to worry about having two values in your item - just implement correct comparator.
Assuming that you are asked this at 2011, it would be good do find out how your sort is meant to be used. Depending on environment where this sort will be used, you may consider parallel processing (using multiple threads). That may drive your choice of sorting algorithm.
I want to write a program to implement an array-based stack, which accept integer numbers entered by the user.the program will then identify any occurrences of a given value from user and remove the repeated values from the stack,(using Java programming language).
I just need your help of writing (removing values method)
e.g.
input:6 2 3 4 3 8
output:6 2 4 8
Consider Collection.contains (possibly in conjunction with Arrays.asList, if you are so unfortunate), HashMap, or Set.
It really depends on what you have, where you are really going, and what silly restrictions the homework/teacher mandates. Since you say "implement an array-based stack" I am assuming there are some silly mandates in which case I would consider writing a custom arrayContains helper* method and/or using a secondary data-structure (Hash/Set) to keep track of 'seen'.
If you do the check upon insertion it's just (meta code, it's your home work :-):
function addItem (i) begin
if not contains(stack, i) then
push(stack, i)
end if
end
*You could use the above asList/contains if you don't mind being "not very efficient", but Java comes with very little nice support for Arrays and thus the recommendation for the helper which is in turn just a loop over the array returning true if the value was found, false otherwise. (Or, perhaps return the index found or -1... your code :-)
Assuming that the "no-duplicates" logic is a part of the stack itself, I would do the following:
1) Implement a helper method:
private boolean remove(int item)
This method should scan the array, and if it finds the item it should shrink the array by moving all subsequent items one position backwards. The returned value indicates whether a removal took place.
2) Now it is easy to implement the push method:
public void push(int item) {
if (!remove(item)) {
arr[topPos++] = item;
}
}
Note that my solution assumes there is always enough space in the array. A proper implementation should take care of resizing the array when necessary.
The question is an interesting (or troubling) one in that it breaks the spirit of the stack to enforce such a constraint. A pure stack can only be queried about its top element.
As a result, doing this operation necessarily requires treating the stack not as a stack but as some other data structure, or at least transferring all of the data in the stack to a different, intermediate data structure.
If you want to accomplish this from within the stack class itself, others' replies will prove useful.
If you want to accomplish this from outside of the stack, using only the traditional methods of a stack interface (push() and pop()), your algorithm might look something like this:
Create a Set of Integers to keep track of values encountered so far.
Create a second stack to hold the values temporarily.
While the stack isn't empty,
Pop off the top element.
If the set doesn't contain that element yet, add it to the set and push it onto the second stack.
If the set does contain the element, that means you've already encountered it and this is a duplicate. So ignore it.
While the second stack isn't empty,
Pop off the top element
Push the element back onto the original stack.
There are various other ways to do this, but I believe all would require some auxiliary data structure that is not a stack.
override the push method and have it run through the stack to determine whether the value already exists. if so, return false otherwise true (if you want to use a boolean return value).
basically, this is in spirit of the answer posted by Mr. Schneider, but why shrink the array or modify the stack at all if you can just determine whether a new item is a duplicate or not? if it's a duplicate, don't add it and the array does not need to be modified. am i missing something?