-2

I'm trying to use different lists & sets and test the needed time. The method should be flexible enough to test other possible classes. Currently I'm able to use the List-classes but with the HashSet I get an error.

Anybody know how to use the test-class with HashSet andLinkedList`?

ArrayList<String> arrList = new ArrayList<String>();
LinkedList linklist = new LinkedList();
HashSet<String> hash = new HashSet<String>();

test(arrList);
test(linklist);
test(hash);

private static <T> void test(List<String> t) {
   start = System.nanoTime();
   for(int i=0; i < 1000; i++) {    
      t.add(r);
      time = System.nanoTime() - start;
   }
   System.out.println("Add: " + time);
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
Zaram
  • 19

3 Answers3

4

Define your method to take a Collection<String> as Collection<T> is the super interface for Set<T> and List<T>.

private static void test(Collection<String> t) { ... }
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
  • 4
    I'd include a short explanation for why that works, ie that list inherits from collection – ifly6 Jun 11 '18 at 12:56
3

The common interface for ArrayList, LinkedList and HashSet is java.util.Collection. You should declare the test method as:

private static <T> void test(Collection<String> t) {
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
3

When you need to unify method signature to take different collection types, use the least restrictive common base type or interface:

  • In cases when your method must make modifications to the collection, use Collection<E> interface; this is what you need in your particular case.
  • In case your method does not need to modify the collection, only read its content, use Iterable<E> interface instead.

The rationale to this approach is that the higher you go up the interface hierarchy, the more applicable your method becomes. For instance, if all you need is read-only access, you could pass your own classes implementing a small interface Iterable<E>, instead of having to implement a large number of methods in Collection<E> interface.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523