aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections and Generics...help me... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Collections and Generics...help me..." Watch "Collections and Generics...help me..." New topic
Author

Collections and Generics...help me...

kathir vel
Ranch Hand

Joined: Jul 03, 2007
Posts: 92
Hi All,

pgm 1:


mport java.util.*;
abstract class Animal {
public abstract void checkup();
}
class Dog extends Animal {
public void checkup() { // implement Dog-specific code
System.out.println("Dog checkup");
}
}
class Cat extends Animal {
public void checkup() { // implement Cat-specific code
System.out.println("Cat checkup");
}
}
class Bird extends Animal {
public void checkup() { // implement Bird-specific code
System.out.println("Bird checkup");
}
}


public class AnimalDoctorGeneric2 {

public void checkAnimals(ArrayList<Animal> animals) //Line 1
for(Animal a : animals) {
a.checkup();
}
}
public static void main(String[] args) {
// make ArrayLists instead of arrays for Dog, Cat, Bird
List<Animal> dogs = new ArrayList<Animal>(); //Line 2
dogs.add(new Dog());
dogs.add(new Dog());
List<Animal> cats = new ArrayList<Animal>();
cats.add(new Cat());
cats.add(new Cat());
List<Animal> birds = new ArrayList<Animal>();
birds.add(new Bird());
// this code is the same as the Array version
AnimalDoctorGeneric1 doc = new AnimalDoctorGeneric1();
// this worked when we used arrays instead of ArrayLists
doc.checkAnimals(dogs); // Line3
doc.checkAnimals(cats);
doc.checkAnimals(birds);
}
}


pgm 2:

import java.util.*;

class base2
{

static void chk(ArrayList<Byte> b)
{System.out.println("Method");
}
public static void main(String[] s)
{
List<Byte> t=new ArrayList<Byte>();
chk(t);
}
}

I am using the same pgm1 Line1 ,Line2, Line 3 concepts in pgm2. pgm1 is compiles and runs.But pgm2 is not compiling and gives this error.List cannot be applied to ArrayList.But why pgm1 is compiling?Anyboby please clarify this.Advance Thanks.
wong sheena
Greenhorn

Joined: Apr 07, 2007
Posts: 23
because of this line "static void chk(ArrayList<Byte> b)"

ArrayList implements List interface so you cannot pass a List reference variable to this method.

change to "static void chk(List<Byte> b)"
will be ok.
kathir vel
Ranch Hand

Joined: Jul 03, 2007
Posts: 92
Thanks for the reply.Pgm1 is working fine. I was using wrong class i.e AnimalDoctorGeneric1 instead of 2.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections and Generics...help me...