user3437216
user3437216

Reputation: 11

how to pass a arraylist object of one class to generic method which is having object as its parameter in java

Address and name are 2 class which is having id and address as variables. there is a method called getHashMApById to that method i am passing ArrayList obj as parameter. while calling the function i am passing a to the method which is a object of ArrayList but i am geeting error saying i cant pass "a" to the method.

public static void main(......){
ArrayList<Address> a=new ArrayList<Address>();
...
...
HashMap h=new HashMap();
h=getHashMapById(a);
....
...
ArrayList<Name> n-new ArrayList<Name>();
....
...
h=getHashMApById(n);
....
....
.....
}
public static HashMap<String,Object> getHashMapbyId(ArrayList<Object> obj){
.......
..........
}

can i do like this or not? if not please help me with the solution

thanks in advancce.

Upvotes: 1

Views: 1168

Answers (2)

Vinay Veluri
Vinay Veluri

Reputation: 6855

You can do something like this, in your static method,

 private static void print(List<?> objectList) {
    System.out.println(objectList.size());
}

Upvotes: 0

Ray
Ray

Reputation: 3201

A collection of Addresses is not the same as a collection of Objects. Read this http://www.javacodegeeks.com/2011/04/java-generics-quick-tutorial.html - especially the part on subtyping.

You can save your implementation by defining a generic type parameter for the map method:

public static <E> HashMap<String, E> getHashMapbyId(ArrayList<E> obj) {

Upvotes: 1

Related Questions