Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #27729

Re: Parameterized collection catch-22

From markspace <markspace@nospam.nospam>
Newsgroups comp.lang.java.programmer
Subject Re: Parameterized collection catch-22
Date 2014-03-11 11:14 -0700
Organization A noiseless patient Spider
Message-ID <lfnjq6$t9m$1@dont-email.me> (permalink)
References <6f84734b-69d5-471c-b041-8d37dd5657e5@googlegroups.com>

Show all headers | View raw


On 3/11/2014 9:36 AM, zapanaz_googlegroups@hotmail.com wrote:
 > public void mergeAddressInfo(List<? extends AddressInfo> list1,
                 List<? extends AddressInfo> 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<BillingInfo>'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 <? extends AddressInfo>.  So it's perfectly 
legal to pass one of each to the mergeAddressInfo() method.

List<BillingInfo> b = ...;
List<ShippingInfo> 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 <A extends AddressInfo> void  mergeAddressInfo( List<A> a,
                 List<A> 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.

<http://docs.oracle.com/javase/tutorial/java/generics/capture.html>
<http://docs.oracle.com/javase/tutorial/java/generics/methods.html>

Back to comp.lang.java.programmer | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread


Thread

Parameterized collection catch-22 zapanaz_googlegroups@hotmail.com - 2014-03-11 09:36 -0700
  Re: Parameterized collection catch-22 markspace <markspace@nospam.nospam> - 2014-03-11 11:14 -0700
    Re: Parameterized collection catch-22 zapanaz_googlegroups@hotmail.com - 2014-03-16 17:04 -0700
      Re: Parameterized collection catch-22 Lew <lewbloch@gmail.com> - 2014-03-22 15:42 -0700
        Re: Parameterized collection catch-22 zapanaz_googlegroups@hotmail.com - 2014-03-23 16:35 -0700
  Re: Parameterized collection catch-22 Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2014-03-12 09:51 -0700
    Re: Parameterized collection catch-22 zapanaz_googlegroups@hotmail.com - 2014-03-16 17:06 -0700

csiph-web