I am trying to write a recursive method to reverse all elements in a queue.
In an abstract class myQueue which implements Queue< T > interface is my reverse method:
public void reverse() {
T temp = dequeue();
Queue<T> bufferQueue = new Queue<T>();
if(!(temp == null)){
bufferQueue.enqueue(temp);
}
if(!(isEmpty())) {
reverse();
}else{
while(!(bufferQueue.isEmpty())){
Queue.enqueue(bufferQueue.dequeue);
}
}
}
The interface Queue< T > has the following methods which are complete(and implicitly do as defined):
public boolean isEmpty();
public int size();
public void enqueue(T e);
public T dequeue();
public T front();
My goal:
In my reverse method, I am aiming to constantly dequeue (remove first element) from my Original Queue recursively till my queue is empty. Every time I dequeue I will place that object in a temporary Queue. When my queue is empty, than I do enqueue from my temp queue back in to my original Queue.
My first problem is defining a new temporary queue, in my case bufferQueue. I get the following:
1. ERROR at solution.java (at line 12)
Queue<T> bufferQueue = new Queue<T>();
^^^^^
Cannot instantiate the type Queue<T>
Queue is an interface. You can't create an instance of an interface.
Check the JavaDoc for Queue and choose a Class that implements Queue instead:
https://docs.oracle.com/javase/7/docs/api/java/util/Queue.html
What you are trying to accomplish is surprisingly simple and doesn't require recursion at all, just the available methods on a concrete class, like ArrayDeque + your custom reverse method. Also, you don't need the intermediate bufferQueue. This should work nicely:
public class MyQueue<T> extends ArrayDeque<T>{
public void reverse() {
T[] contents = toArray(T[]);
clear();
if(contents != null){
for(int i = contents.length-1; i >= 0; i--){
add(contents[i]);
}
}
}
}
You need to have a concrete type there not T, T is not possible when isntantiating.
I have been trying to implement a Queue using 2 stacks and was able to implement enqueue and dequeue operation correctly. Now i tried implementing getMin in it and got into a bit of problem.
Theory
In theory, to implement a getMin operation, we store two values in stack- The value and minimum till now. So we will be storing these values in this way- {7, 5, 9, 2, 1} ==> {(7,7), (5,5), (9,5), (2,2), (1,1)}. Now if we try to insert 0, first we will check if 0 is less than current min. If true then we will insert it as (0,0) else (0, last_min_value).
My Approach
I created a class name Element like this
class Element<T>{
T element;
T min;
Element(T element, T min){
this.element = element;
this.min = min;
}
}
My Problem
Well code doesn't compile or better to say I don't understand the concept of compareTo at all, when should i use it. I believe i can understand it in a better way, if i directly use it in my program rather than doing some dummy question
import java.util.Stack;
import java.util.LinkedList;
import java.util.Comparator;
class Element<T>{
T element;
T min;
Element(T element, T min){
this.element = element;
this.min = min;
}
}
class MyQueue<T>{
Stack <Element<T>>s_old;
Stack <Element<T>>s_new;
MyQueue(){
s_old = new Stack<Element<T>>();
s_new = new Stack<Element<T>>();
}
void enqueue(T ele){
if(s_old.empty())
s_old.push(new Element<T>(ele,ele));
else{
if(ele.compareTo(s_old.peek().min) < 0) //problem occurs here
s_old.push(new Element<T>(ele, ele));
else
s_old.push(new Element<T>(ele, s_old.peek().min));
}
}
T deque(){
if(s_new.empty()){
while(!s_old.empty()){
s_new.push(s_old.pop());
}
}
return s_new.pop().element;
}
}
class QueueMain{
public static void main(String args[]){
MyQueue <Integer>q = new MyQueue<Integer>();
q.enqueue(1);
q.enqueue(2);
//System.out.println(q.s_old);
System.out.println(q.deque());
}
}
The problem is quite simple:
In java we have 2 ways to compare an object.
The compared class can either implement the Comparable Interface or use a Comparator.
Here is how you can make the above code work with the Comparable interface:
Comparable
class Element<T extends Comparable<T>> implements Comparable<Element<T>>
{
T element;
T min;
Element(T element, T min)
{
this.element = element;
this.min = min;
}
#Override
public int compareTo(Element<T> ele)
{
int elementCompareResult = ele.element.compareTo(element);
if (elementCompareResult == 0){
// element is the same, Compare by min
return min.compareTo(ele.min);
}
return elementCompareResult;
}
}
Notice how I demand that T will extend Comparable himself, otherwise I would have no way of compering it.
Edit:
Also, the myQueue class looks like this now:
class MyQueue<T extends Comparable<T>>
Comperator
Now lets say I dont want to ask for a T that implements comparable.
I could ask for a Comparator in the constructor like so:
class MyQueue<T>
{
Stack<Element<T>> s_old;
Stack<Element<T>> s_new;
Comparator<T> comparator;
MyQueue(Comparator<T> comparator)
{
s_old = new Stack<Element<T>>();
s_new = new Stack<Element<T>>();
this.comparator = comparator;
}
void enqueue(T ele)
{
if (s_old.empty())
{
s_old.push(new Element<T>(ele, ele));
}
else
{
if (comparator.compare(ele, s_old.peek().min) < 0) //problem occurs here
{
s_old.push(new Element<T>(ele, ele));
}
else
{
s_old.push(new Element<T>(ele, s_old.peek().min));
}
}
}
T deque()
{
if (s_new.empty())
{
while (!s_old.empty())
{
s_new.push(s_old.pop());
}
}
return s_new.pop().element;
}
}
Now I will need to create a comparator for by T.
Lets say my T is an Integer:
class MyAwesomeIntegerComparator implements Comparator<Integer>{
#Override
public int compare(Integer first, Integer second)
{
return first - second;
}
}
Now using this:
public static void main(String args[])
{
MyQueue<Integer> q = new MyQueue<Integer>(new MyAwesomeIntegerComparator());
q.enqueue(1);
q.enqueue(2);
//System.out.println(q.s_old);
System.out.println(q.deque());
}
Summery
To sum up:
In java you can either compare by making the desired class compareable
Or by making it a separated Comperable just for it and then use it when needed.
Why would I ever need a Comperable ?
Lets say I have a class cow.
Sometimes I want to compare it by amount of milk it gives.
Sometime by wight.
I'l make a method that accepts any Cow comperator and it wont care what comparator its using.
For example, the Arrays.sort() method does exactly that.
sort(T[] a, Comparator<? super T> c)
How this helps.
My problem is this: I have an iterator class which is supposed to iterate through elements in a given data structure, <E> let's say, but what I have managed to accomplish is that when I pass in the data structure it will iterate the data structure itself.
ie. DynamicIterator it = new DynamicIterator(da);
say da is an array the output will be [1,2,3,4,5,6] instead of 1,2,3,4,5,6
My issue is, more than anything, understanding the generally accepted practice for dealing with this more than the issue itself.
edit for code:
public class X<E>
{
private final E[] rray;
private int currentIndex = 0;
public X(E... a)
{
//if the incoming array is null, don't start
if(a == null)
{
System.out.println("Array is null");
System.exit(1);
}
//set the temp array (rray) to the incoming array (a)
this.rray = a;
}
//hasNext element?
public boolean hasNext()
{
return rray.length > currentIndex;
}
//next element (depends on hasNext())
public E next()
{
if (!hasNext())
{
System.out.println("Element doesn't exist, done");
System.exit(1);
}
return rray[currentIndex++];
}
//return array
public E[] access()
{
return rray;
}
}
You won't be able to do this with a completely generic parameter <E> - how would you iterate through a Throwable, for example? What your class X does at the moment is accept any number of objects in its constructor, and then simply returns each of those objects in turn.
If you restricted the bounds of the objects passed in to implement e.g. Iterable, then you can actually start to "look inside" them and return their contents:
public class X<E> {
private final Iterator<E> it;
public X(Iterable<E> a) {
it = a.iterator();
}
public boolean hasNext() {
return it.hasNext();
}
public E next() {
return it.next();
}
}
Although this doesn't really accomplish anything different to just using a.iterator() directly instead of an instance of X...
I'm working on sorted Queues like a Priority Queue. I already did it with a List, and it already worked great. Now I'd like to do it with a array. But I have a little logical Problem with add a new Element and insert it into the sorted array.
The final output should be like that:
Priority: 5 Value: x
Priority: 4 Value: iso
.... (and so on)
So the Element with the highest Priorithy should be on index = 0.
I just don't know (and yes I know it's really simply to switch it, but I just can't do it :/) how to do it...
I already tried a few things but I'm stuck... :/ can please anyone help?
Here's my code:
public class Queue {
private QueueElem[] a;
public Queue(int capacity)
{
QueueElem[] tempQueue = new QueueElem[capacity];
a= tempQueue;
}
public void enqueue(int p, String v)
{
QueueElem neu = new QueueElem(p,v);
int i=0;
while(i<a.length)
{
if (a[i] == null)
{
a[i] = neu;
break;
}
i++;
}
}
public void writeQueue()
{
int i=0;
while((i< a.length) && (a[i] != null))
{
System.out.println("Priority: " + a[i].priority + " Value: " + a[i].value);
i++;
}
}
public static void main(String args[])
{
Queue neu = new Queue(10);
neu.enqueue(4,"iso");
neu.enqueue(2,"abc");
neu.enqueue(5,"x");
neu.enqueue(1,"abc");
neu.enqueue(4,"bap");
neu.enqueue(2,"xvf");
neu.enqueue(4,"buep");
}
}//end class Queue
class QueueElem {
int priority;
String value = new String();
public QueueElem(){ }
public QueueElem(int p, String v)
{
this.priority = p;
this.value = v;
}
public int getPrio()
{
return this.priority;
}
public String getValue()
{
return this.value;
}
}
It would be better if you interpreted your array as a max-heap. That is the typical way to implement priority queue.
What you're looking for, if you're trying to maintain a sorted array for your priority queue, is to implement insertion sort (sort of; you don't have an unsorted array to start with. You have an empty array that you simply add to, while maintaining a sorted order). Every time you insert a new element, you will iterate through the array to find the correct spot and then insert it there, after shifting the elment currently at that spot, and everything after it one spot down. Note that this is not as performant as implementing this using a heap, since at worst you have O(n) performance every time you insert, whereas with a heap you have O(logn).
I don't understand why anyone would want to work with raw arrays... especially now that you have implemented it with a List.
If you want to see how to insert an element in a raw array, look in the code of ArrayList, since underneath it uses a raw array. You'll have to move all the elements to right of the insertion point, which you could copy in a loop, or by using System.arraycopy(). But the nastiest part is that you will likely have to create a new array since the array size increases by one when you add an element (it depends if you are using an array that has exactly the size of your data, or a larger array, as is done in ArrayList).
I am trying to print out all the elements of a List, however it is printing the pointer of the Object rather than the value.
This is my printing code...
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
Could anyone please help me why it isn't printing the value of the elements.
The following is compact and avoids the loop in your example code (and gives you nice commas):
System.out.println(Arrays.toString(list.toArray()));
However, as others have pointed out, if you don't have sensible toString() methods implemented for the objects inside the list, you will get the object pointers (hash codes, in fact) you're observing. This is true whether they're in a list or not.
Since Java 8, List inherits a default "forEach" method which you can combine with the method reference "System.out::println" like this:
list.forEach(System.out::println);
Here is some example about getting print out the list component:
public class ListExample {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
// TODO: First create your model and add to models ArrayList, to prevent NullPointerException for trying this example
// Print the name from the list....
for(Model model : models) {
System.out.println(model.getName());
}
// Or like this...
for(int i = 0; i < models.size(); i++) {
System.out.println(models.get(i).getName());
}
}
}
class Model {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
System.out.println(list);//toString() is easy and good enough for debugging.
toString() of AbstractCollection will be clean and easy enough to do that. AbstractList is a subclass of AbstractCollection, so no need to for loop and no toArray() needed.
Returns a string representation of this collection. The string representation consists of a list of the collection's elements in the
order they are returned by its iterator, enclosed in square brackets
("[]"). Adjacent elements are separated by the characters ", " (comma
and space). Elements are converted to strings as by
String.valueOf(Object).
If you are using any custom object in your list, say Student , you need to override its toString() method(it is always good to override this method) to have a meaningful output
See the below example:
public class TestPrintElements {
public static void main(String[] args) {
//Element is String, Integer,or other primitive type
List<String> sList = new ArrayList<String>();
sList.add("string1");
sList.add("string2");
System.out.println(sList);
//Element is custom type
Student st1=new Student(15,"Tom");
Student st2=new Student(16,"Kate");
List<Student> stList=new ArrayList<Student>();
stList.add(st1);
stList.add(st2);
System.out.println(stList);
}
}
public class Student{
private int age;
private String name;
public Student(int age, String name){
this.age=age;
this.name=name;
}
#Override
public String toString(){
return "student "+name+", age:" +age;
}
}
output:
[string1, string2]
[student Tom age:15, student Kate age:16]
Use String.join()
for example:
System.out.print(String.join("\n", list));
The Java 8 Streams approach...
list.stream().forEach(System.out::println);
The objects in the list must have toString implemented for them to print something meaningful to screen.
Here's a quick test to see the differences:
public class Test {
public class T1 {
public Integer x;
}
public class T2 {
public Integer x;
#Override
public String toString() {
return x.toString();
}
}
public void run() {
T1 t1 = new T1();
t1.x = 5;
System.out.println(t1);
T2 t2 = new T2();
t2.x = 5;
System.out.println(t2);
}
public static void main(String[] args) {
new Test().run();
}
}
And when this executes, the results printed to screen are:
t1 = Test$T1#19821f
t2 = 5
Since T1 does not override the toString method, its instance t1 prints out as something that isn't very useful. On the other hand, T2 overrides toString, so we control what it prints when it is used in I/O, and we see something a little better on screen.
Or you could simply use the Apache Commons utilities:
https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/ArrayUtils.html#toString-java.lang.Object-
List<MyObject> myObjects = ...
System.out.println(ArrayUtils.toString(myObjects));
Consider a List<String> stringList which can be printed in many ways using Java 8 constructs:
stringList.forEach(System.out::println); // 1) Iterable.forEach
stringList.stream().forEach(System.out::println); // 2) Stream.forEach (order maintained generally but doc does not guarantee)
stringList.stream().forEachOrdered(System.out::println); // 3) Stream.forEachOrdered (order maintained always)
stringList.parallelStream().forEach(System.out::println); // 4) Parallel version of Stream.forEach (order not maintained)
stringList.parallelStream().forEachOrdered(System.out::println); // 5) Parallel version ofStream.forEachOrdered (order maintained always)
How are these approaches different from each other?
First Approach (Iterable.forEach)-
The iterator of the collection is generally used and that is designed to be fail-fast which means it will throw ConcurrentModificationException if the underlying collection is structurally modified during the iteration. As mentioned in the doc for ArrayList:
A structural modification is any operation that adds or deletes one or
more elements, or explicitly resizes the backing array; merely setting
the value of an element is not a structural modification.
So it means for ArrayList.forEach setting the value is allowed without any issue. And in case of concurrent collection e.g. ConcurrentLinkedQueue the iterator would be weakly-consistent which means the actions passed in forEach are allowed to make even structural changes without ConcurrentModificationExceptionexception being thrown. But here the modifications might or might not be visible in that iteration.
Second Approach (Stream.forEach)-
The order is undefined. Though it may not occur for sequential streams but the specification does not guarantee it. Also the action is required to be non-interfering in nature. As mentioned in doc:
The behavior of this operation is explicitly nondeterministic. For
parallel stream pipelines, this operation does not guarantee to
respect the encounter order of the stream, as doing so would sacrifice
the benefit of parallelism.
Third Approach (Stream.forEachOrdered)-
The action would be performed in the encounter order of the stream. So whenever order matters use forEachOrdered without a second thought. As mentioned in the doc:
Performs an action for each element of this stream, in the encounter
order of the stream if the stream has a defined encounter order.
While iterating over a synchronized collection the first approach would take the collection's lock once and would hold it across all the calls to action method, but in case of streams they use collection's spliterator, which does not lock and relies on the already established rules of non-interference. In case collection backing the stream is modified during iteration a ConcurrentModificationException would be thrown or inconsistent result may occur.
Fourth Approach (Parallel Stream.forEach)-
As already mentioned no guarantee to respect the encounter order as expected in case of parallel streams. It is possible that action is performed in different thread for different elements which can never be the case with forEachOrdered.
Fifth Approach (Parallel Stream.forEachOrdered)-
The forEachOrdered will process the elements in the order specified by the source irrespective of the fact whether stream is sequential or parallel. So it makes no sense to use this with parallel streams.
I have faced similar problems. My code:
List<Integer> leaveDatesList = new ArrayList<>();
.....inserted value in list.......
Way 1: printing a list in a for loop
for(int i=0;i<leaveDatesList.size();i++){
System.out.println(leaveDatesList.get(i));
}
Way 2: printing the list in a forEach, for loop
for(Integer leave : leaveDatesList){
System.out.println(leave);
}
Way 3: printing the list in java 8
leaveDatesList.forEach(System.out::println);
You haven't specified what kind of elements the list contains, if it is a primitive data type then you can print out the elements.
But if the elements are objects then as Kshitij Mehta mentioned you need to implement (override) the method "toString" within that object - if it is not already implemented - and let it return something meaning full from within the object, example:
class Person {
private String firstName;
private String lastName;
#Override
public String toString() {
return this.firstName + " " + this.lastName;
}
}
It depends on what type of objects stored in the List, and whether it has implementation for toString() method. System.out.println(list) should print all the standard java object types (String, Long, Integer etc). In case, if we are using custom object types, then we need to override toString() method of our custom object.
Example:
class Employee {
private String name;
private long id;
#Override
public String toString() {
return "name: " + this.name() +
", id: " + this.id();
}
}
Test:
class TestPrintList {
public static void main(String[] args) {
Employee employee1 =new Employee("test1", 123);
Employee employee2 =new Employee("test2", 453);
List<Employee> employees = new ArrayList(2);
employee.add(employee1);
employee.add(employee2);
System.out.println(employees);
}
}
For a list of array of String
list.forEach(s -> System.out.println(Arrays.toString((String[]) s )));
For loop to print the content of a list :
List<String> myList = new ArrayList<String>();
myList.add("AA");
myList.add("BB");
for ( String elem : myList ) {
System.out.println("Element : "+elem);
}
Result :
Element : AA
Element : BB
If you want to print in a single line (just for information) :
String strList = String.join(", ", myList);
System.out.println("Elements : "+strList);
Result :
Elements : AA, BB
System.out.println(list); works for me.
Here is a full example:
import java.util.List;
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
final List<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
System.out.println(list);
}
}
It will print [Hello, World].
list.stream().map(x -> x.getName()).forEach(System.out::println);
I wrote a dump function, which basicly prints out the public members of an object if it has not overriden toString(). One could easily expand it to call getters.
Javadoc:
Dumps an given Object to System.out, using the following rules:
If the Object is Iterable, all of its components are dumped.
If the Object or one of its superclasses overrides toString(), the "toString" is dumped
Else the method is called recursively for all public members of the Object
/**
* Dumps an given Object to System.out, using the following rules:<br>
* <ul>
* <li> If the Object is {#link Iterable}, all of its components are dumped.</li>
* <li> If the Object or one of its superclasses overrides {#link #toString()}, the "toString" is dumped</li>
* <li> Else the method is called recursively for all public members of the Object </li>
* </ul>
* #param input
* #throws Exception
*/
public static void dump(Object input) throws Exception{
dump(input, 0);
}
private static void dump(Object input, int depth) throws Exception{
if(input==null){
System.out.print("null\n"+indent(depth));
return;
}
Class<? extends Object> clazz = input.getClass();
System.out.print(clazz.getSimpleName()+" ");
if(input instanceof Iterable<?>){
for(Object o: ((Iterable<?>)input)){
System.out.print("\n"+indent(depth+1));
dump(o, depth+1);
}
}else if(clazz.getMethod("toString").getDeclaringClass().equals(Object.class)){
Field[] fields = clazz.getFields();
if(fields.length == 0){
System.out.print(input+"\n"+indent(depth));
}
System.out.print("\n"+indent(depth+1));
for(Field field: fields){
Object o = field.get(input);
String s = "|- "+field.getName()+": ";
System.out.print(s);
dump(o, depth+1);
}
}else{
System.out.print(input+"\n"+indent(depth));
}
}
private static String indent(int depth) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<depth; i++)
sb.append(" ");
return sb.toString();
}
I happen to be working on this now...
List<Integer> a = Arrays.asList(1, 2, 3);
List<Integer> b = Arrays.asList(3, 4);
List<int[]> pairs = a.stream()
.flatMap(x -> b.stream().map(y -> new int[]{x, y}))
.collect(Collectors.toList());
Consumer<int[]> pretty = xs -> System.out.printf("\n(%d,%d)", xs[0], xs[1]);
pairs.forEach(pretty);
public static void main(String[] args) {
answer(10,60);
}
public static void answer(int m,int k){
AtomicInteger n = new AtomicInteger(m);
Stream<Integer> stream = Stream.generate(() -> n.incrementAndGet()).limit(k);
System.out.println(Arrays.toString(stream.toArray()));
}
try to override toString() method as you want that the element will be printend.
so the method to print can be this:
for(int i=0;i<list.size();i++){
System.out.println(list.get(i).toString());
}
Solusion of your problem for java 11 is:
String separator = ", ";
String toPrint = list.stream().map(o -> String.valueOf(o)).collect(Collectors.joining(separator));
System.out.println(toPrint);
You can try:
for 2D(or more)
System.out.println(Arrays.deepToString(list.toArray()));
for 1D
System.out.println(Arrays.toString(list.toArray()))
List<String> textList= messageList.stream()
.map(Message::getText)
.collect(Collectors.toList());
textList.stream().forEach(System.out::println);
public class Message {
String name;
String text;
public Message(String name, String text) {
this.name = name;
this.text = text;
}
public String getName() {
return name;
}
public String getText() {
return text;
}
}