Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9007359
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T01:40:06+00:00 2026-06-16T01:40:06+00:00

Within my method readList , I would like to build a java.util.List of a

  • 0

Within my method readList, I would like to build a java.util.List of a user-defined type (the concrete list type is a parameter). I don’t want to restrict readList to ArrayList or LinkedList however; the user might supply his own java.util.List implementation. The method might also cache the list if possible, so the method needs to return the list. I tried a few things. Which one of the following is the ‘best’ API in your view, or is there another, even better one?

The following compiles, but I get the compiler warning: “Type safety: The expression of type ArrayList needs unchecked conversion to conform to ArrayList”, so it’s not really a good solution:

void classParameter() {
    ArrayList<String> a = readList(ArrayList.class);
    LinkedList<String> b = readList(LinkedList.class);
}

<X, T extends List<X>> T readList(Class<T> clazz) {
    try {
        return clazz.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

The following compiles, but I still get the compiler warning, plus it doesn’t actually work as expected:

void classTypeParameters() {
    ArrayList<String> a = readList(ArrayList.class, String.class);
    LinkedList<String> b = readList(LinkedList.class, Integer.class);
}

<T extends List<X>, X> T readList(Class<T> clazz, Class<X> type) {
    try {
        return clazz.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

The following works, and is my personal favorite. It checks the list type. What is a bit dangerous is somebody could by mistake forget to assign the result. This could be solved by renaming readList to readListWithTemplate or so, it would be more obvious the return value is to be used. It’s similar to List.toArray(T[] a):

void template() {
    ArrayList<String> a = readList(new ArrayList<String>());
    LinkedList<String> b = readList(new LinkedList<String>());
    // wrong usage:
    List<String> c = new LinkedList<String>();
    readList(c);
}

@SuppressWarnings("unchecked")
<X, T extends List<X>> T readList(T template) {
    try {
        return (T) template.getClass().newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

The “super token type” works as well, but might be bit hard to understand
for developers not familiar with this pattern, and in Eclipse
I get the warning “Empty block should be documented”, which I would like to avoid:

void superTypeToken() {
    ArrayList<String> a = readList(new ListType<ArrayList<String>>() {});
    LinkedList<String> b = readList(new ListType<LinkedList<String>>() {});
}

abstract static class ListType<X extends List<?>> {
    // super type token class
}

@SuppressWarnings("unchecked")
<X, T extends List<X>> T readList(ListType<T> t) {
    try {
        Type type = t.getClass().getGenericSuperclass();
        if (!(type instanceof ParameterizedType)) {
            throw new IllegalArgumentException("Missing type parameters");
        }
        ParameterizedType pt = (ParameterizedType) type;
        type = pt.getActualTypeArguments()[0];
        pt = (ParameterizedType) type;
        Class<?> listClass = (Class<?>) pt.getRawType();
        return (T) listClass.newInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Which one do you prefer? Or is there a better solution?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T01:40:08+00:00Added an answer on June 16, 2026 at 1:40 am

    I would probably delegate to another builder class. A small class that just knows how to create new lists. It provides better runtime safety as it does not rely on the assumption that the given class has a default constructor. Maybe not so useful with lists as we should always be able to create an empty list, but more important with other types of class.

    eg.

    public interface EmptyListBuilder {
    
        public <E> List<E> newList();
    
        public static final EmptyListBuilder ARRAY_LIST_BUILDER = 
                new EmptyListBuilder() {
    
            public <E> List<E> newList() {
                return new ArrayList<E>();
            }
        };
    }
    

    As shown by the static field you can also provide a default implementation for a few standard classes.

    Use the class like this:

    <T> List<T> readList(EmptyListBuilder builder) {
        List<T> list = builder.newList();
        // read in elements
        return list;
    }
    

    You lose being able to know exactly what type of list you have, but of that’s an issue then it sounds like you’re trying to do something a little odd.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I would like to convert from a set to a List within a method
I would like to use Twisted non-blocking getPage method within a webapp, but it
I am using Java to build a simple method within a class that will
If you have code (objective-c) within a method that you would like to condense
I have a spring bean that I get like this within a method- repAppCaller
How should I call a method within a defined class from a template class
If I have a instance method and within this method I do something like
I have a onsubmit dojo/method within a custom templated widget like so: try {
Is there any method within Perl which would allow me to get the object
I am trying to use the Java paint method within an ActionListener. However, when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.