what I am trying to do is, I have a UTILITY package and I wanted to make a class GetArray with a method get, which creates an array and return that array, also I wanted to make this method generic
so I could create what ever type of array I wanted to.
The problem is in the statement arr[i] = in.next();
in the loop.
ie, how would I assign values depending on the type of the array I want to build
public class GetArray {
/**
* @param takes a scanner varable
* @return returns an array of all the elements you specify
*/
public static <T> int[] get(Scanner in) {
System.out.print("enter array size : ");
int ar_size = in.nextInt();
System.out.print("arr elements: ");
T arr[] = new T[ar_size];
for (int i = 0; i < ar_size; i++) {
arr[i] = in.next();
}
return arr;
}
}
I will be calling this method from my main.java, and therefore I am passing the scanner to it
To have the correct array type, you need to pass the class of the elements:
UPDATE: but Scanner.next always returns a String, so I'm afraid You'll have to test the class to know which method of Scanner to use: