Results 1 to 2 of 2
  1. #1
    Nhatmeister is offline Member
    Join Date
    Aug 2013
    Rep Power

    Default Generic and ArrayList

    Hi Everyone,
    Here is an example of my code.

    import java.util.*;
    public class Driver {

    public static void main(String[] args) {

    ArrayList<Generic> dArray = new ArrayList<Generic>();

    Generic<Double> myDouble = new Generic<Double>(1.0);

    public static <T> void standardDeviation(ArrayList<T> list){
    for(int i=0; i<list.size();i++){
    T g = (T) list.get(i); //T is Object type instead of Generic
    g.getNumber(); //this method is in Generic, but not visible here.

    this method call Driver.<Generic>standardDeviation(dArray);
    shouldn't "Generic" be plugin for all <T> ? and the typeCast should make list.get(i) a Generic type ?

    Thanks much

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Generic and ArrayList

    Your choice of the class name, Generic, makes this hard to discuss. First, you should declare your List as ArrayList<Generic<Double>> since Generic is a generic type (ugh!). Then you can just do this:
    Java Code:
    T g = list.get(i);
    for any type T and you won't get a class cast exception. However, suppose you had declared List to be ArrayList<Foo> which doesn't have a getNumber method, visible or not. How would the use of your method distinguish between the two list forms? If you are going to expect your method to support a specific method of a generic class, then use an interface and incorporate it into the type parameter with an extends.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 12
    Last Post: 07-07-2011, 09:49 PM
  2. generic in arraylist
    By katturv in forum New To Java
    Replies: 4
    Last Post: 10-02-2010, 10:33 PM

Tags for this Thread

Posting Permissions

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