Guest User

Untitled

a guest
Oct 24th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. public class GenericsType<T> {
  2.  
  3. private T t;
  4.  
  5. public T get(){
  6. return this.t;
  7. }
  8.  
  9. public void set(T t1){
  10. this.t=t1;
  11. }
  12.  
  13. public static void main(String args[]){
  14. GenericsType<String> type = new GenericsType<>();
  15. type.set("Pankaj"); //valid
  16.  
  17. GenericsType type1 = new GenericsType(); //raw type
  18. type1.set("Pankaj"); //valid
  19. type1.set(10); //valid and autoboxing support
  20. }
  21. }
  22.  
  23. public interface MyInyerface<E> {
  24. void print(E e);
  25. }
  26.  
  27. public class MyClass implements MyInyerface<String> {
  28. @Override
  29. public void print(String s) {
  30.  
  31. }
  32.  
  33.  
  34. class MyClassInteger implements MyInyerface<Integer>{
  35.  
  36. @Override
  37. public void print(Integer integer) {
  38.  
  39. }
  40. }
  41. }
  42.  
  43. ArrayList&ltString> stringList = new ArrayList&ltString>(); // список строк
  44. ArrayList&ltInteger> intList = new ArrayList&ltInteger>(); // список чисел
  45. stringList.add("123"); // OK
  46. stringList.add(123); // Ошибка!
  47. intList.add("123"); // Ошибка!
  48. intList.add(123); // OK
  49.  
  50. class SomeClass < T > {
  51. ...
  52. private T value;
  53. public T getValue() { ... }
  54. }
  55.  
  56. SomeClass< Integer > intInstance = new SomeClass< Integer >();
  57. SomeClass< ArrayList > listInstance = new SomeClass< ArrayList>();
  58. ....
  59. int i = intInstance.getValue(); // OK
  60. int j = listInstance.getValue(); // Error!!!
  61. ArrayList list = listInstance.getValue(); // OK
Add Comment
Please, Sign In to add comment