Getting error: incompatible types: int cannot be converted to T. I want to build a queue using linked list that can store items of different data types. Please suggest ways on how can i pass values belonging to different data types into the generic function add().
public void main(String args[])
{
MyQueue<T> q=new MyQueue<T>();
q.add(10);
q.add("Hello");
}
public void add(T item)
{
QueueNode<T> t=new QueueNode<T>(item);
if(last!=null)
{
last.next=t;
}
last=t;
}
T is a placeholder for a Type, but you can't declare T like this since T must be a known type. You want something like this. Here T is a known type which is passed to QueueNode and MyQueue.
package com.company;
import java.util.ArrayList;
import java.util.List;
class QueueNode<T> {
private T nodeVal;
T getNodeVal() {
return nodeVal;
}
void setNodeVal(T nodeVal) {
this.nodeVal = nodeVal;
}
QueueNode(T nodeVal) {
this.nodeVal = nodeVal;
}
}
class MyQueue<T> {
private List<QueueNode<T>> actualQueue = new ArrayList<QueueNode<T>>();
public List<QueueNode<T>> getActualQueue() {
return actualQueue;
}
public void enqueue(T t) {
actualQueue.add(new QueueNode<>(t));
}
public QueueNode<T> dequeue() {
return actualQueue.remove(0);
}
}
class Main {
public static void main(String[] args) {
MyQueue<Integer> integerQueue = new MyQueue<Integer>();
integerQueue.enqueue(1);
integerQueue.enqueue(2);
integerQueue.enqueue(3);
integerQueue.getActualQueue().forEach(e -> System.out.print(e.getNodeVal() + " ")); //prints 1 2 3
System.out.println();
integerQueue.dequeue();
integerQueue.getActualQueue().forEach(e -> System.out.print(e.getNodeVal() + " ")); //prints 2 3
System.out.println();
integerQueue.dequeue();
integerQueue.getActualQueue().forEach(e -> System.out.print(e.getNodeVal() + " ")); //prints 3
System.out.println();
}
}
You should change de T for Object. This way you can place whatever data type you want and then you can use a foreach, for example:
public static void main(String args[])
{
Queue<Object> queues=new LinkedList<>();
queues.add(10);
queues.add("Hello");
for(Object queue:queues){
System.out.println(queue);
}
}
The Generic class gives solution more bigger.
Also consider that int is a primitive data type and it's not a class. In this case Integer is the class that uses int.