Reputation: 6381
I have multiple ArrayList for a different type, and how to pass them to a single function?
For example,
ArrayList<String> mStringList = new ArrayList<>();
ArrayList<Interge> mIntList = new ArrayList<>();
passArraylist(0,mStringList)
passArraylist(1,mIntList )
private void passArraylist(int tag , ArrayList<?> list){
if(tag == 0){
//how to change list to ArrayList<String>
}else if(tag == 1){
//how to change list to ArrayList<Interge>
}
}
How to pass the different type of ArrayList to a single function and get the correct type in function?
Upvotes: 0
Views: 1508
Reputation: 688
When you want to pass different types of objects you use Generics
, but depending on what you intend to do it might be better to use separate methods per type.
However what you are stumbling on here is the type erasure at compile time of Java Generics
, so you no longer know what type of list is passed.
Your method should be implemented with a cast as below, however it is not type safe.
Meaning you can pass the wrong tag with the wrong list.
public static void main(String[] args) {
List<String> mStringList = new ArrayList<String>();
List<Integer> mIntList = new ArrayList<Integer>();
// Your method, but type safety is lost.
passArraylist(0, mStringList);
passArraylist(1, mIntList);
passArraylist(0, mIntList); -> compiles, but will cause a RuntimeException
}
private void passArraylist(int tag, List<?> list){
if(tag == 0){
List<String> stringList = (List<String>) list;
String item = stringList.get(0);
System.out.println("with value ["+ item +"] and type ["+ item.getClass() +"]");
}else if(tag == 1){
List<Integer> intList = (List<Integer>) list;
Integer item = intList.get(0);
System.out.println("with value ["+ item +"] and type ["+ item.getClass() +"]");
}
}
It's better to use the following approach to have type safety.
Meaning if you pass a List<String>
, it will be used as a List<String>
and the get
method will automatically return a String
object.
public static void main(String[] args) {
List<String> mStringList = new ArrayList<String>();
List<Integer> mIntList = new ArrayList<Integer>();
// New method, with type safety.
passArraylist(mStringList, String.class);
passArraylist(mIntList, Integer.class);
passArraylist(mIntList, String.class); -> won't compile
}
private <T> void passArraylist(List<T> list, Class<T> clazz){
if(clazz == String.class){
System.out.print("Print my String ");
}else if(clazz == Integer.class){
System.out.print("Print my Integer ");
}
T item = list.get(0);
System.out.println("with value ["+ item +"] and type ["+ item.getClass() +"]");
}
The actual functionality you wish to obtain in your method is not entirely clear, so this might not be what you need. In that case elaborate on what your method should accomplish and we'll continue from there.
Upvotes: 1