1
public class G<x> { x i; } public class E { public static void main(String[] args) { G<Integer> b1 = new G<Integer>(); G<String> b2 = new G<String>(); b1.i = 50; b2.i = "start"; System.out.println(b1.i); System.out.println(b2.i); } } 

How this case is different from the other case given below

public class G<x> { x i; } public class E { public static void main(String[] args) { G b1 = new G(); G b2 = new G(); b1.i = 50; b2.i = "start"; System.out.println(b1.i); System.out.println(b2.i); } } 

I know While you are making the Object of G class we have to define the type argument for generics but without passing the type argument it will work ..The output will be shown. So why my teacher says that Type argument is important though the code will run without it also.

There is a difference in both cases. In first case we are passing an integer type argument through the reference variable b1 and String type argument through the b2 reference variable but in the second case we are not doing this. And by not doing this In second case the data type will be object type. Both code will give you same answer, but my teacher says that you have to use always 1case .So my question was why he said so because both code will give you same answer so why cant we use 2 case

0

2 Answers 2

1

I assume you actually mean this compiles:

G b1=new G(); G b2=new G(); b1.i=50; b2.i="start"; System.out.println(b1.i); System.out.println(b2.i); 

This happens to work as PrintStream.println has an overload for Object, so will take any object. Usually you would want to call a more interesting method.

Incidentally there can still be a difference. Due to the peculiar design of PrintStream, this code will do something different.

G b1=new G(); G<char[]> b2=new G<>(); b1.i="start".toCharArray(); b2.i="start".toCharArray(); System.out.println(b1.i); System.out.println(b2.i); 

You will get warnings. Generally you want to treat warnings as if they were errors.

Sign up to request clarification or add additional context in comments.

2 Comments

this code is way different from mine. In your code the 2 line will give error but in my case you will not find any errors and exceptio while running the code
One more thing G<char[]> b2=new G<char[]>(); by doing this you will get the result. what will this line b1.i="start".toCharArray(); give the output and why
0

The first case is typesafe. In the first case you have declared that b1.i accepts only Integer so you can't by mistake assign i.e. String into it. You can rely on it containing Integer.

In the second case you can assign arbitrary descendant of Object into b1.i so typesafety is gone. You can't be so sure that b1.i contains particular type.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.