I wanted to create a static method which prints the contents of an array.I wrote one for String[] as below
public static void print(String[] a){
for(String x : a){
System.out.print(x+", ");
}
System.out.println();
}
I thought I could create a method which takes in a generic type ,and modified the code as below
public class ArrayPrinting<E> {
public static void printArray(E[] a){
for(E x : a){
System.out.print(x+", ");
}
System.out.println();
}
public static void main(String[] args) {
String[] a = {"A","B","C","D","E"};
}
}
But,this gives a compiler error
'Cannot make a static reference to the non-static type E'
So,how do I create such a method?or is it impossible ? Since this is a static method, I wonder how I can invoke the method without creating an instance. A call like
ArrayPrinting<E>.printArray(a) doesn't look right ..
Can someone help?
Try this
public class ArrayPrinting {
public static <E> void printArray(E[] a){
for(E x : a){
System.out.print(x+", ");
}
System.out.println();
}
public static void main(String[] args) {
String[] a = {"A","B","C","D","E"};
ArrayPrinting.printArray(a);
}
}
Ravi already covered the proper syntax for a generic method. I just want to point out that this particular method doesn't need to be generic:
public static void printArray(Object[] a) {
for (Object x : a) {
System.out.print(x + ", ");
}
System.out.println();
}
The reason this works is array covariance - a String[] is an Object[].
Class's generic type parameters are for class level variables and methods (instance variables and methods).So you can't use it.
You can handle it by declaring type parameter in the method itself:
public static <E> void printArray(E[] a){
.............
}
public class ArrayPrinting<E> {
public void printArray(E[] a){
for(E x : a){
System.out.print(x+", ");
}
System.out.println();
}
public static void main(String[] args) {
String[] a = {"A","B","C","D","E"};
new ArrayPrinting().printArray(a);
}
}
Related
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.
I know this error occurs when we try downcasting values but in my code I am not able to figure ooout where have I downcasted the values.
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show(5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(short N){
System.out.println(N*2);
}
}
class TestDemo2{
public Void show(String S){
System.out.println(S);
}
}
This error is occurring due to obj.show(5).
Two fixes`you can do any:
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show((short)5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(short i){
System.out.println(i*2);
}
}
class TestDemo2{
public void show(String S){
System.out.println(S);
}
}
Second Version
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show(5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(int i){
System.out.println(i*2);
}
}
class TestDemo2{
public void show(String S){
System.out.println(S);
}
}
Try changing the short N, in public void show(short N) from test Demo to int.
try to cast the int first.
obj.show((short)5);
Number 5 is treated by default as integer which is passed to method with short argument.
obj.show((short)5);
Also for future reference, java errors as well as exceptions are very detailed, giving you the exact line number where the issue occurred. That should help you identify the code segment where the issue is.
I have this code.
public class TypeInterface{
public static void main(String [] args){
StringLengthLambda myLambda = s -> s.length();
System.out.print(myLambda.getLength("abc"));
}
interface StringLengthLamdba{
int getLength(String s);
}
}
Can this code be modified to
StringLengthLambda myLambda = s.length()
or
any other way to shorten this?
I can't think of any way to write a shorter lambda, but you could use a method reference:
StringLengthLambda myLambda = String::length;
You don't even need the package protected interface StringLengthLambda. You could just go with:
public static void main(String [] args){
Function<String, Integer> myLambda = String::length;
System.out.print(myLambda.apply("abc"));
}
If you want different "length-computation-methods" on "abc" you could even go with:
public class TypeInterface {
public static void main(String[] args) {
print(String::length);
}
private static void print(StringLengthLambda myLambda) {
System.out.print(myLambda.getLength("abc"));
}
#FunctionalInterface
interface StringLengthLambda {
int getLength(String s);
}
}
I can't figure out the problem in this.
public class Trying {
public static void main(String[] args) {
new Trying().go("hi", 1);
new Trying().go("hi", "world", 2);
}
public void go(String... y, int x) {
System.out.print(y[y.length - 1] + " ");
}
}
A varargs argument, like String... y has to be the last variable in a method declaration. Change your declaration to:
public void go(int x, String... y) {
A varargs argument must be the last variable in a method declaration
public class Trying {
public static void main(String[] args) {
new Trying().go(1,"hi");
new Trying().go(2,"hi", "world");
}
public void go(int x,String... y) {
for(int i=0;i<x;i++){
System.out.println(y[i]);
}
}
}
For More
There is an attempt to declare Regular parameter after the varargs parameter which is illegal.
public void go(String... y, int x) //Error
Restriction of varags:
varargs must be declared last
2.There must be only one varargs parameter
change your method to public void go(int x, String... y)
Can i use the following code? It's not throwing any error at the Object but at obj.i. Is this a legal way of using an object? Also, how many ways can i create an object other than using the normal syntax obj s = new obj();
public class Test {
static int i;
static Test obj;
obj.i = 10; //am getting a compilation error here "Syntax error on token "i", VariableDeclaratorId expected after this token"
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}
You need to place a static block around the obj.i assignment statement for this to work:
public class Test {
static int i;
static Test obj;
static { obj.i = 10; }
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}
This is not, you didn't initialize. Furthermore you might not want to use static.
public static void main(String [] args) {
int i = 10;
Test obj = new Test();
obj.setI(i);
System.out.println("my objects I = "+ obj.getI());
}
now in your Test object
public class Test {
private int i;
public void setI(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
}