Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to create a method that return generic type in Java

4 Answers

0 votes
public class MyClass {
    public static <T> T getValue(T[] array, int index) {
        return array[index];
    }
        
    public static void main(String args[]) {
        
        String[] array = {"java", "c", "c++", "c#"};
        
        String value = MyClass.<String>getValue(array, 1);
        
        System.out.println(value);
    }
}
   
   
   
   
/*
run:
  
c
  
*/

 



answered Nov 14, 2023 by avibootz
0 votes
public class MyClass {
    public static <T> T getValue(T[] array, int index) {
        return array[index];
    }
        
    public static void main(String args[]) {
        
        Integer[] array = {2, 5, 8, 9, 0, 3};
        
        Integer value = MyClass.<Integer>getValue(array, 2);
        
        System.out.println(value);
    }
}
   
   
   
   
/*
run:
  
8
  
*/

 



answered Nov 14, 2023 by avibootz
0 votes
public class MyClass {
    public static <T> void getValues(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }
         
    public static void main(String args[]) {
         
        Double[] array = {2.3, 5.28, 8.19, 9.9, 0.03, 3.14};
         
        MyClass.<Double>getValues(array);
    }
}
    
    
    
    
/*
run:
   
2.3
5.28
8.19
9.9
0.03
   
*/

 



answered Nov 14, 2023 by avibootz
0 votes
public class MyClass {
    public static <T> void getValues(T[] array) {
        for (T element : array) {
            System.out.println(element);
        }
    }
         
    public static void main(String args[]) {
         
        Character[] array = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' };
        
        getValues(array);
    }
}
    
    
    
    
/*
run:
   
a
b
c
d
e
f
g
   
*/

 



answered Nov 14, 2023 by avibootz

Related questions

1 answer 123 views
123 views asked Apr 19, 2020 by avibootz
1 answer 192 views
192 views asked Jan 8, 2016 by avibootz
1 answer 146 views
2 answers 118 views
118 views asked Mar 21, 2023 by avibootz
1 answer 205 views
...