0% found this document useful (0 votes)
87 views1 page

Java Composite Pattern for Value Containers

This document defines an interface called ValueContainer that represents a container of integer values that can be iterated over. It defines two classes that implement this interface: SingleValue, which contains a single integer value, and ManyValues, which contains multiple integer values stored in an ArrayList. It also defines a MyList class that extends ArrayList and can hold either SingleValue or ManyValues objects, and includes a method to sum all the integer values in the contained ValueContainer objects.

Uploaded by

Mario Zamora
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
87 views1 page

Java Composite Pattern for Value Containers

This document defines an interface called ValueContainer that represents a container of integer values that can be iterated over. It defines two classes that implement this interface: SingleValue, which contains a single integer value, and ManyValues, which contains multiple integer values stored in an ArrayList. It also defines a MyList class that extends ArrayList and can hold either SingleValue or ManyValues objects, and includes a method to sum all the integer values in the contained ValueContainer objects.

Uploaded by

Mario Zamora
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.

package [Link].

exercise;

import [Link].*;

interface ValueContainer extends Iterable<Integer> {}

class SingleValue implements ValueContainer


{
public int value;

public SingleValue(int value)


{
[Link] = value;
}

@Override
public Iterator<Integer> iterator()
{
return [Link](value).iterator();
}
}

class ManyValues extends ArrayList<Integer> implements ValueContainer


{
}

class MyList extends ArrayList<ValueContainer>


{
public MyList(Collection<? extends ValueContainer> c)
{
super(c);
}

public int sum()


{
int result = 0;
for (ValueContainer c : this)
{
for (int i : c)
{
result += i;
}
}
return result;
}
}

You might also like