java - Restrict method to RandomAccess List -


i've method operates on list, removing duplicates. algorithm efficient on lists implementing randomaccess. prevent misuse , disappointing performance, i'm wondering how enforce randomaccess restriction. randomaccess interface not extend list unfortunately, sort of need make variable 2 types @ once.

i declare method accept arraylist rather list, other list types can implement randomaccess (for example, lists returned collections.synchronizedlist , collections.checkedlist), , don't want block those.

i tried generics, couldn't construct working syntax:

public <t> void process(<list<t> extends randomaccess> list) {     ... } 

i do:

if (!(list instanceof randomaccess))     throw new unsupportedoperationexception("randomaccess list required"); 

but restriction enforced @ run time, less robust.

help?

you need use multiple bounds, indicated ampersand (&):

public <t,l extends list<t> & randomaccess> void process(l  list) 

putting (non-compilable, unless remove second call) class:

public class main {      public static void main(string[] argv)     throws exception     {         main x = new main();         x.process(new arraylist<string>());         x.process(new linkedlist<string>());     }      public <t,l extends list<t> & randomaccess> void process(l  list) {      } } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -