Prasad
Prasad

Reputation: 139

convert list of objects to list of strings and generics

Following scheme works fine dealing with strings/primitives. But when dealing with lists it gives type cast error in getObj(). The types used are dynamic and needs this generic use. Is there any better way to achieve it ?

public static Object obj;
    static public T getObj<T>()
    {
        return (T)obj;
    }
    private static string getStr()
    {
        return "some string";
    }
    private static List<Object> getList()
    {
        List<Object> res = new List<object>();
        Object o = "str1";
        res.Add(o);

        o = "str2";
        res.Add(o);
        return res;
    }

    public static void Main()
    {
        obj = getStr();
        string s = getObj<string>();

        obj = getList();
        List<string> slist = getObj<List<string>>();
    }

Upvotes: 1

Views: 10068

Answers (2)

Ugam Kumar Sharma
Ugam Kumar Sharma

Reputation: 11

hope this will be help you!!!

 public List<Object> lisObject() {
        List<Object> listProduct = new ArrayList<Object>();
        try {
            con.setAutoCommit(false);
            callableStatement = con.prepareCall("call listType()");
            rs = callableStatement.executeQuery();
            while(rs.next()){
                pType = new ProductType();
                pType.setPtypeId(rs.getInt(1));
                pType.setPName(rs.getString(2));
                pType.setDesc(rs.getString(3));
                pType.setCatMaster(new CatMaster(rs.getInt(4), rs.getString(5)));
                listProduct.add(pType);
            }
            con.commit();
        } catch (Exception e) {
            System.out.println("Failed to Fetching List of Type Object:"+e);
        }finally{

        }
        return listProduct;
    }


%%%%%%%%%%%%%%%%%
Fetching Data
%%%%%%%%%%%%%%%%
List<Object> listpro  =(List<Object>)dao.lisObject();

int i=0;enter code here
for(Iterator<Object> itr = listpro.iterator();itr.hasNext();){                          
ProductType p = (ProductType)itr.next();

ProductType is java bean

Upvotes: 1

angelsl
angelsl

Reputation: 395

You're trying to cast a List<Object> to a List<String>. Even if all the contents of the list are of String, the List is still a List<Object>, so you cannot do a direct cast like that.

If you really want to do so, you could use this instead:

List<Object> objList = { ... }; // all strings
List<String> strList = objList.Cast<String>().ToList();

A reason you cannot do a cast from List<Object> to List<String> is because all strings are objects but not all objects are strings; if you casted a List<String> to List<object> and then tried to add an object (that is not a string) to it, the behaviour would be undefined.

Upvotes: 6

Related Questions