• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections and Generics...help me...

 
kathir vel
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.Pgm1 is working fine. I was using wrong class i.e AnimalDoctorGeneric1 instead of 2.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic