list - Is it better to use generics or Object type for a static helper class in Java? -


i writing program other day required me to: frequency of particular object inside arraylist<string>, remove occurrences of given item, etc., etc. not specified list interface. decided write own helper class , wanted make reusable possible. decided specify list parameter type of collection use class implementing list interface. these classes defined using generics, , did not know class type item removed be. either had define static helper methods generically since static class can not contain generic types explicitly, or define class type of object removed object. implemented in both ways, see below, wondering if there benefits using 1 on other.

some further questions on topic:

  1. why able work around reference of generic type in static context defining in method header rather class header?
  2. when using static method, why not have declare class type in usage? i.e. listtools_v2.getfrequencyof(arraylist<string> items, string s) still works.

implementation using object class type

import java.util.list;  /** general utility class performing needed operations     on class implementing list interface **/  public class listtools {      public static void removealloccurrences(list items, object o) {         while(items.contains(o)) {             items.remove(o);         }     }      public static int getfrequencyof(list items, object o) {         int frequency = 0;         for(object item : items) {             if(item.equals(o)) {                 frequency++;             }         }         return frequency;     }  } 

implementation using generics

import java.util.list;  /** general utility class performing needed operations     on class implementing list interface. implementation     uses generics maximize reusability. **/  public class listtools_v2 {      public static <e> void removealloccurrences(list<e> items, e o) {         while(items.contains(o)) {             items.remove(o);         }     }      public static <e> int getfrequencyof(list<e> items,e o) {         int frequency = 0;         for(e item : items) {             if(item.equals(o)) {                 frequency++;             }         }         return frequency;     }  } 

both operations operate on equality (.equals()) between given object reference , elements inside list, , equality not limited objects of same type, shouldn't restrict o same type type parameter of list.

however, raw types bad, shouldn't use raw type list. should parameterize wildcard when there no need constrain type variable against anything:

public static void removealloccurrences(list<?> items, object o) public static int getfrequencyof(list<?> items, object o) 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -