Results 1 to 3 of 3
  1. #1
    batya is offline Member
    Join Date
    Nov 2009
    Posts
    4
    Rep Power
    0

    Cool How can I cast object to Vector?

    I have a Table and ArryList<T>. I want to cast three fields from each elemnt in the ArrayList<T> to Vector, in order to add row to the TableModel..
    what the right way to do it?
    Last edited by batya; 11-19-2009 at 09:04 AM.

  2. #2
    r035198x is offline Senior Member
    Join Date
    Aug 2009
    Posts
    2,388
    Rep Power
    7

    Default

    What have you tried?

  3. #3
    zweibieren is offline Senior Member
    Join Date
    Aug 2009
    Location
    Pittsburgh, PA
    Posts
    284
    Rep Power
    5

    Default

    The short answer is that using a cast will not work.
    The code must actually create a Vector or an array.
    Suppose that an ArrayList named myList has elements of type ListElement
    and the three desired fields are a, b, and c, of types TypeA, TypeB, and TypeC.
    Suppose further that the TableModel is named tm.

    The code called for by your query could be
    Java Code:
    	// add row for field a
    	Vector<TypeA> aVec = new Vector<TypeA>();
    	for (ListElement elt : myList) aVec.add(elt.a);
    	tm.addRow(aVec);
    	// repeat the above for fields b and c
    Your query is confusing because it is the reverse of the usual case.
    In the usual case, if a table was based on an ArrayList<T>,
    each element of the ArrayList would correspond to one row of the table.
    For this case the code would be simpler with an array:
    Java Code:
    	for (ListElement elt : myList) {
    		tm.addRow(new Object[]{elt.a, elt.b, elt.c});
    	}
    Simplest of all would be to create a TableModel subclass
    that fetches data directly from the ArrayList.

Similar Threads

  1. Passing a Vector object to a function
    By evapisces in forum New To Java
    Replies: 4
    Last Post: 09-27-2008, 03:18 AM
  2. Search a object in a vector
    By TalhaS in forum New To Java
    Replies: 2
    Last Post: 04-30-2008, 02:05 PM
  3. URGENT: Sorting a vector of object by an element
    By doobybug in forum New To Java
    Replies: 1
    Last Post: 03-12-2008, 06:37 PM
  4. How to cast an Object into a specific type (Integer/String) at runtime
    By mailtogagan@gmail.com in forum Advanced Java
    Replies: 2
    Last Post: 12-03-2007, 01:04 PM
  5. How can I cast Object as an int
    By romina in forum New To Java
    Replies: 1
    Last Post: 07-18-2007, 11:20 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •