简体   繁体   中英

Java and use of generics?

I want to be able to pass 2 generic types to my class.

  • First generic type can be anything
  • Second generic type must be a list of a certain object.

How can I achieve this? The following code doesn't compile, it just shows what I'm aiming for.

public class AbstractGroupedAdapter<T, List<Y>> extends ArrayAdapter<Y> {

   protected Map<T, List<Y>> groupedItems;

   protected T getHeaderAtPosition(int position) {
      // return the correct map key
   }

   protected Y getItemAtPosition(int position) {
      // return the correct map value
   }

   @Override
   public int getCount() {
      return groupedItems.size() + groupedItems.values().size();
   }
}

In Java, you can't qualify generic type parameters on their name declaration. Instead, declare the type parameter normally and use it in a generic bound, ie:

public class AbstractGroupedAdapter<T,Y> extends ArrayAdapter<List<Y>> {


  protected Map<T, List<Y>> groupedItems;

   protected T getHeaderAtPosition(int position) {
      // return the correct map key
   }

   protected Y getItemAtPosition(int position) {
      // return the correct map value
   }

   @Override
   public int getCount() {
      return groupedItems.size() + groupedItems.values().size();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM