Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: markspace Newsgroups: comp.lang.java.programmer Subject: Re: Parameterized collection catch-22 Date: Tue, 11 Mar 2014 11:14:27 -0700 Organization: A noiseless patient Spider Lines: 43 Message-ID: References: <6f84734b-69d5-471c-b041-8d37dd5657e5@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Tue, 11 Mar 2014 18:14:31 +0000 (UTC) Injection-Info: mx05.eternal-september.org; posting-host="9358cda03e1e0dfd3c4b757daa608707"; logging-data="30006"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+hzbo6mzce0BeYTSW7RMIj1K8m0yNia4g=" User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:24.0) Gecko/20100101 Thunderbird/24.3.0 In-Reply-To: <6f84734b-69d5-471c-b041-8d37dd5657e5@googlegroups.com> Cancel-Lock: sha1:muoV9qYhErr7h4DzQyHc+k7/LPI= Xref: csiph.com comp.lang.java.programmer:27729 On 3/11/2014 9:36 AM, zapanaz_googlegroups@hotmail.com wrote: > public void mergeAddressInfo(List list1, List list2) { > list1.add(1, list2.get(0)); > } > > But Java won't allow this, it won't allow the add(). All it knows > about what list2 contains is that it's something that descends from > AddressInfo, so even if I pass in 2 List's, inside the > code it doesn't know they're the same classes. Yes. Consider that your two subtypes, BillingInfo and ShippingInfo, both match the wildcard . So it's perfectly legal to pass one of each to the mergeAddressInfo() method. List b = ...; List s = ...; x.mergeAddressInfo( b, s ); // works So Java is telling you you can't call list1.add() because it assumes you don't want to mix up a list of two different types. So you have to tell the compiler that both parameters are of the same type. One way to do that is to use a generic method: public void mergeAddressInfo( List a, List b ) {... Now the compiler knows that a and b are of the same type. It will enforce that when you call the method (give you an error) and it will allow operations that make sense for lists of the same type. (Not compiled or tested.) C.f. the Java tutorial.