A collection class is a class that can store a collection of objects. . it manipulates groups of data as a single unit. there are few collection interfaces
The Set interface extends Collection but forbids duplicates.They have few properties such as
They contains only one instance of each item
They may be finite or infinite.
They can define abstract concepts
The List interface extends Collection, allows duplicates, and introduces positional indexing.
The Map interface extends neither Set nor Collection.
map is a special kind of set. It is a set of pairs, each pair representing a one-directional
mapping from one element to another (eg. student ID and name).
2. Take a look at the following code. Your intention was to store objects that belong to the Animal hierarchy to an ArrayList. A subclass that belongs to Animal hierarchy is a Dog class. There are other classes such as a Truck class and a Melon class. Assume that one object of each subclass type exists.
ArrayList arrayList = new ArrayList();
arrayList.add(dog);
arrayList.add(animal);
arrayList.add(truck);
arrayList.add(melon);
a. Has the code met the designer’s objective of storing objects of type Animal in an ArrayList?
no it hasn't it only stores the elements in the array list not the objects of type animal.
b. Write a piece of code to extract Animal objects out of the ArrayList.
for (Iterator
Animal temp = iter.next();
System.out.println(temp.getName());
}
How can you ensure that only objects of type Animal be stored in the ArrayList?
public static void main(String args[]) {
ArrayList
animals.add(new Animal(“dog”, "bow"));
animals.add(new Animal(“cat”, "meow"));
animals.add(new Animal(“tiger”, "zimba"));
animals.add(new Animal(“elephant”, "Dumbo"));
}
public Animal (String species, String name) {
this.species = species;
this.name = name;
}
No comments:
Post a Comment