Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Daniele Futtorovic Newsgroups: comp.lang.java.programmer Subject: Re: Store Suppliers in a map Date: Wed, 10 Apr 2019 19:07:09 +0200 Organization: A noiseless patient Spider Lines: 76 Message-ID: References: <88a3b286-0d96-425e-ac82-c02e3ebcc84a@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit Injection-Date: Wed, 10 Apr 2019 17:07:37 -0000 (UTC) Injection-Info: reader02.eternal-september.org; posting-host="dee46868515977d2c77fad2cbcfea7d5"; logging-data="24664"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX194W2oVSdW1zMbQI5xOX3Oc" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Thunderbird/60.6.1 Cancel-Lock: sha1:7P7m6xbJIu/3EcS0Q2LojZStGdE= In-Reply-To: <88a3b286-0d96-425e-ac82-c02e3ebcc84a@googlegroups.com> X-Antivirus-Status: Clean Content-Language: en-US X-Antivirus: AVG (VPS 190410-2, 04/10/2019), Outbound message Xref: csiph.com comp.lang.java.programmer:38895 On 2019-04-10 07:01, mike wrote: > Hi, > > I need to to different suppliers: > > - Supplier > - Supplier > - Supplier> > > Map map= new HashMap<>(); > > How can I define a map ( some similar collection ) to store these different suppliers in? > > When I get it from map what will be the type? The type will be whatever you put in the map, namely, "Supplier". The generic parameter is just sugar. Your Map should be a Map> . You can ease calls to the class with the following method, which makes invocations easier but doesn't give you any type safety: class SupplierHolder { private final Map> map = new HashMap<>(); public void put(String key, Supplier s){ map.put(key, s); } @SuppressWarnings("unchecked") public Supplier get(String key){ // may yield a ClassCastException return (Supplier) map.get(key); } } Thus you could call: SupplierHolder sh = ...; Supplier s = sh.get("key") without casting. If you want type safety, the only approach I can think of involves more complex keys. To wit: final class Key { private final String key; private Key(String s){ this.key = s; } public static final Key KEY_1 = new Key<>("key_1"); public static final Key KEY_2 = new Key<>("key_2"); public static final Key> KEY_3 = new Key<>( "key_3" ); } class SupplierHolder { private final Map, Supplier> map = new HashMap<>(); public void put(Key key, Supplier s){ map.put(key, s); } @SuppressWarnings("unchecked") public Supplier get(Key key){ //may return null, but won't yield a ClassCastException (unless you have called #put with raw types) return (Supplier) map.get(key); } } Note that in this case, the Keys have to be constants in a regular class, and can't be in an Enum, as the Enum won't allow different type parameters for its members. (Also, Class parameter is strictly speaking unnecessary in this example). (Caveat: untested code) -- DF.