So I have this simple code in java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue. The code:
public class MyQueue<T>{
private List<T> body;
// some constructors and helper functions.
//copy constructor
public Queue(List<T> list){
this.body = list;
}
//this is the function
public MyQueue<T> enqueue(T obj){
List<T> temp = new ArrayList<T>(body);
temp.add(obj);
return new Queue<T>(temp);
}
The whole Idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue.
UPDATE For the sake of completing the idea.
1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).
2- As for the helper functions, they are simple:
public T peek(){
if(body.isEmpty()){
thrown new NoSuchElementException();
}
return body.get(0);
}
public int size(){
return body.size();
}
Any ideas? thanks
A queue is a basic data structure and it's hard to make it better than the experts having worked on it. The simplest and fastest general purpose implementation is probably the ArrayDeque and there's hardly anything to improve.
What you're doing is strange at best:
Instead of appending an element, you copy the whole content. Why?
You insert the new element at the highest index, why? This way your poll (dequeue, remove, whatever) must remove the index at element 0, which is slow for ArrayList.
Actually, I have no idea how your poll may look like. In any case, your enqueue doesn't do what I'd expect from a method called like this.
Use a LinkedList instead of an ArrayList. You don't need indexed access in a queue, but you do need fast enqueue/dequeue. If you need indexed access. It isn't really a queue at all. And just use the add() method, don't create a whole new queue every time. Your enqueue() method should return 'this', or void. And don't allow the caller to supply the list: create your own.
Related
it has been to long since i asked here ..
I have this homework which has this Q Remove The Bottom Of The Stack I did it
good but not great ..
but now i have a Q is how to reverse the stack i did it by using another stack
is there a better way
this is what i did :
public static<T> void removeLast(LinkedList<T> st)
{
LinkedList<T> store = new LinkedList<>();
while (!st.eamty()){
store.push(st.pop());
}
store.pop();
while(!store.eamty()){
st.push(store.pop());
}
}
some src I found
Most efficient way to reverse a stack and add to an ArrayList
https://www.careercup.com/question?id=12689669
I'd made the following instead:
public static<T> void removeLast(LinkedList<T> st)
{
return st.removeLast();
}
But this is not a queue meant to be used and is also quite "expensive" operation ...
First of all, LinkedList<T> is not just a Stack. It is a List. In fact, it is a list class with a specific operation to removing the last element. (The removeLast method is defined by the Deque interface which LinkedList implements. The Deque abstraction is a "double ended queue"; i.e. something that can act as both a FIFO and a LIFO - a queue and a stack.)
So if you are able to the fact that this representation of a stack is implemented as a linked list, then the solution is to call that method.
On the other hand, if you are required / restricted to implementing your removeLast using only "stack-like" methods in the LinkedList API, then your approach of popping all elements to a temporary stack is probably as good as you can get.
I have a class which maintains a list of features of the class. These features change infrequently compared to the reads. The reads are almost always iterations through the feature list. Because of this, I'm using a CopyOnWriteArrayList.
I want to have a function like this:
function Feature[] getFeatures() {
.. implementation goes here ..
}
I admit, the reason may be a bit of laziness. I'd like to write code like this:
for (Feature f: object.getFeatures()) {
.. do something interesting ..
}
rather than this:
Iterator<Feature> iter = object.getFeatureIterator();
while (iter.hasNext()) {
Feature f = iter.next();
.. do something interesting ..
}
The main question is - am I being lazy here? I'm going to follow this pattern a lot, and I think the first chunk of code is far easier to maintain. Obviously, I would never change the underlying array, and I would put this in the documentation.
What is the proper way to handle this situation?
Just call the toArray method on the list:
public Feature[] getFeatures() {
return this.featureList.toArray(new Feature[this.featureList.size()]);
}
Note that the foreach syntax can be used with all the Iterable objects, and List is Iterable, so you could just have
public List<Feature> getFeatures() {
return this.features;
}
and use the same foreach loop. If you don't want the callers to modify the internal list, return an unmodifiable view of the list:
public List<Feature> getFeatures() {
return Collections.unmodifiableList(this.features);
}
I don't understand your reason: return a List<Feature>, use your CopyOnWriteArrayList or an unmodifiable copy, and use the foreach. Why do you specifically want an array?
Class CopyOnWriteArrayList implements Iterable, which is all you need to use the sugared for loop syntax. You don't need to get hold of an Iterator explicitly in the case you describe above.
Did you find that it doesn't compile?
you can clone the List
public List<Feature> getFeatures() {
return (List<Feature>)this.features.clone();
}
cloning a copyOnWriteArrayList doesn't copy the underlying array
The copy-on-write (COW) nature of a CopyOnWriteArrayList object means that at every modification of the list you get a new instance of its underlying array, with all entries but the modification copied from the previous instance.
To give you a coherent view while iterating over the list when other threads keep changing its content, a call to the iterator() method ties the iterator to the array, not the list. When a modification changes the list, a new array holds the new content, but the iterator continues to run through the old array that was available when iterator() was called. This means that you walk through a coherent snapshot of the list.
(In contrast, a loop such as for (int i = 0; i < list.size(); ++i) doSomethingWith(list.get(i)); does not protect you from modifications from other threads, and you may easily run off the end of the list if between a call to list.size() and the corresponding list.get(i), some elements have been deleted!)
Since the for each style for-loop uses iterators under the covers, you get this coherence guarantee. You also get it when using the forEach() method. This iterates (using array indexing) within the array available at the time forEach() is invoked.
Finally, the clone() method essentially takes a similar snapshot. If your code is the only place you use the cloned version, or you make it unmodifiable, you'll be consulting the original snapshot. The COW nature of the original shields your copy from changes to the original. If you don't want to rely on clone(), which has issues, you can copy out the list data, but that involves at least copying the array with another allocation.
Even if it's easy to make an handle make, but I wonder if there is any famous helper help to get the size of a list or to get the last object of a list. I think it is really a popular requirements, but I couldn't found one.
size = list==null? 0: list.size();
lastObject = isEmpty(list)? null:list.get(list.size() - 1).
Thanks,
Those don't seem all that helpful to me. I try to initialize my lists so they're not null, so the first one is not useful at all. As for the second, it's no more useful to get back a possibly-null object (which then has to be tested to see if it's null) than it is to check the size of the list first.
There isn't a helper method for this AFAIK. One thing you should make sure is that when writing your own helper utility, pay special attention to your target collection. If it is a List, avoid using get(index) since it is not very efficient for a linked list implementation. If it is an ArrayList or in general any collection which implements RandomAccess, get is very efficient. The most generic way would be to obtain an iterator for the last element and invoke next() on it if it exists.
public static <T> T getLast(final List<T> list) {
final ListIterator<T> listIterator = list.listIterator(list.size());
return listIterator.hasPrevious() ? listIterator.previous() : null;
}
Google Guava has a getLast method. However, I couldn't find a size method that handles null Collections.
I have a list of Strings and I want to perform the same operation on all of the Strings in the list.
Is it possible without performing a loop?
Well something's got to loop, somewhere - if you want to abstract that into your own method, you could do so, but I don't believe there's anything built into the framework.
Guava has various methods in Iterables to perform projections etc, but if you want to modify the list on each step, I'm not sure there's any support for that. Again, you could write your own method (extremely simply) should you wish to.
When Java eventually gets closures, this sort of thing will become a lot more reasonable - at the moment, specifying the "something" operation is often more effort than it's worth compared with hard-coding the loop, unfortunately.
You could do it recursively, but I don't see why you'd want to. You may be able to find something similar to Python's map function (which, behind the scenes, would either be a loop or a recursive method)
Also note that strings are immutable - so you'll have to create 'copies' anyway.
No. You must loop through the list.
for(String s:yourlist){
dooperation(s);
}
Why do you not want to perform a loop?
If it's computational complexity, then no, it's unavoidable. All methods will essentially boil down to iterating over every item in the list.
If it's because you want something cleaner, then the answer depends on what you think is cleaner. There are various libraries that add some form of functional map, which would end up with something like:
map(list, new Mapper<String, String>() {
public String map(String input) {
return doSomethingToString(input);
}
);
This is obviously more long winded and complex than a simple loop
for (int i = 0; i < list.size(); i += 1) {
list[i] = doSomethingToString(list[i]);
}
But it does offer reusability.
map(list, new DoSomethingToStringMapper());
map(otherlist, new DoSomethingToStringMapper());
But probably you don't need this. A simple loop would be the way to go.
You could use apache commons util.
sorry, you have to iterate through the list somehow, and the best way is in a loop.
Depending on what you mean by no loop, this may interest you:
a map function for java.
http://www.gubatron.com/blog/2010/08/31/map-function-in-java/
...there's still a loop down inside of it.
In Java you'll need to iterate over the elements in the Collection and apply the method. I know Groovy offers the * syntax to do this. You could create an interface for your functions e.g. with an apply method and write a method which takes your Collection and the interface containing the function to apply if you want to add some general API for doing this. But you'll need the iteration somewhere!
Use divide and conquer with multithreaded traversal. Make sure you return new/immutable transformed collection objects (if you want to avoid concurrency issues), and then you can finally merge (may be using another thread which will wake up after all the worker threads finished transformer tasks on the divided lists?).
If lack of memory in creating these intermediate collections, then synchronize on your source collection. Thats the best you can do.
No you have to use a loop for that.
You have to perform the operation on each reference variable to the Strings in the List, so a loop is required.
If its at the List level, obviously there are some operations (removeAll, etc.).
The java API provides special class to store and manipulate group of objects. One Such Class is Arraylist
Note that Arraylist class is in java.util.ArrayList
Create an ArrayList as you would any objects.
import java.util.ArrayList;
//..
ArrayList ajay = new ArrayList();
Here
ArrayList -> Class
ajay -> object
You can optionally specify a capacity and type of objects the Arraylist will hold:
ArrayList ajay<String> = new ArrayList<String>(10);
The Arraylist class provides a number of useful methods for manipulating objects..
The add() method adds new objects to the ArrayList.And remove() method remove objects from the List..
Sample code:
import java.util.ArrayList;
public class MyClass {
public static void main(String[ ] args) {
ArrayList<String> ajay = new ArrayList<String>();
ajay.add("Red");
ajay.add("Blue");
ajay.add("Green");
ajay.add("Orange");
ajay.remove("Green");
System.out.println(colors);
}
}
Output for this Code:
[Red,Blue,Orange]
Accepted answer link is broken and solution offered is deprecated:
CollectionUtils::forAllDo
#Deprecated
public static <T,C extends Closure<? super T>> C forAllDo(Iterable<T> collection, C closure)
Deprecated. since 4.1, use IterableUtils.forEach(Iterable, Closure) instead
Executes the given closure on each element in the collection.
If the input collection or closure is null, there is no change made.
You can use IterableUtils::forEach(Closure c)
Applies the closure to each element of the provided iterable.
I have to write a priotity queye as implementation of the folowing interface:
public interface PQueue<T extends Comparable<T>> {
public void insert( T o ); // inserts o into the queue
public T remove(); // removes object with highest priority (by natural order)
}
I would be glad for some help and clues, becouse I don't even know how to begin with this issue.
I'd start off with something like this. The general idea is that you have an internal list and when you insert a new item you do a binary search to find where it belongs in that list. This way your internal list is always sorted so when you call remove() you just take the last (or first depending on how you're ordering things) item.
Disclaimer: This should be viewed as pseudo-code. I know for a fact there are problems with it. It's only intended to be a starting point.
public class PQueueImpl<T> implements PQueue<T> {
private List<T> internalQueue;
public void insert(T item){
int insertionPoint = Collections.binarySearch(internalQueue, item);
internalQueue.add(insertionPoint, item);
}
public T remove(){
return internalQueue.remove(internalQueue.size() - 1);
}
}
You could look at the source for java.util.PriorityQueue. Their implementation is backed by an Object array and is significantly more complex than the other example I gave, but I'm sure it works and performs much better too.
Priority queues are in practice implemented most commonly as heaps. They can also be implemented as a balanced binary search tree, or any other fast sorted data structure. The key is that the data structure must have very fast (faster than O(n)) max/min, insert, remove and update operations.