Solved

Posted on 2012-09-09

generics problemis to avoid type cast problem is it correct

any way explain advanages of generics

any way explain advanages of generics

6 Comments

```
public class Arithmetic<T> {
public T Add(T input1, T input2) {
return intput1 + input2;
}
}
```

Now if we were going to add two

```
...
public int Add(int input1, int input2) {
return input1 + input2;
}
...
```

Can't you add

```
...
public decimal Add(decimal input1, decimal input2) {
return input1 + input2;
}
...
```

The logic above is exactly the same: perform the addition of two things and return the result. The power of generics is that we do not need to duplicate the logic to account for multiple types. We essentially make the type variable, and we write the class only once, inserting placeholders for the types. Then, we can simply pass the type when we want to work with different types:

```
Arithmetic<int> adder1 = new Arithmetic<int>();
int input1 = 1;
int input2 = 2;
int result1 = adder1.Add(input1, input2);
Arithmetic<decimal> adder2 = new Arithmetic<decimal>();
decimal input3 = 1.0;
decimal input4 = 2.0;
decimal result2 = adder2.Add(input3, input4);
```

I'm sure you'd agree that we can use the function defined immediately above because it is designed to take in only ints.That was supposed to say "can

is it jdkk1.5 feature or jdk1.6 featuresAccording to Wiki, they came with Java 5.

By clicking you are agreeing to Experts Exchange's Terms of Use.

Title | # Comments | Views | Activity |
---|---|---|---|

PGP Decryption code using Bouncy Castle jars | 11 | 69 | |

squareUp challenge | 22 | 80 | |

System.currentTimeMillis() |
15 | 43 | |

basic hardware to learn oop advanced design patterns | 3 | 49 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**7** Experts available now in Live!