• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Rob Spoor
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Carey Brown
Bartenders:

Doubt in ArrayLists

 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

can you tell me what i am doing wrong in the following code. I am unable to figure it out .

import java.util.*;
class ArrList
{
public static void main(String args[])
{
ArrayList<Animal> list = new ArrayList<Animal>();
list.add(new Animal());
list.add(new Animal("Horse"));
list.add(new Animal("Pig"));
list.add(new Animal("Horse"));
list.add(1,new Animal("Fox"));
System.out.println(list.get(2));
System.out.println(list.isEmpty());
System.out.println(list.contains("Horse")); // I am getting False here
System.out.println(list.indexOf("Horse")); // here i am getting -1
System.out.println(list.size());
Iterator<Animal> it = list.iterator();
while(it.hasNext())
{
Animal a= it.next();
System.out.println(a);
}

}
}

class Animal
{
String name;
Animal(String n)
{
name=n;
}
Animal()
{
}
public String toString()
{
return name;
}
}

I am expecting "True" and 2 as answers. Pls help
 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You are looking for String (there's no String in your List), not for Animal.
You should look for Animal objects. Look at Map#contains API to learn on how it works :
http://java.sun.com/j2se/1.4.2/docs/api/java/util/List.html#contains(java.lang.Object)

TIP : you have to override "equals" and "hashCode" in your Animal class
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please use Code Tags when posting code. Thanks!
 
sudha javvadi
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Satou,

Thank you very much for your reply. I finally got it after 2 hours of struggle.

Sudha.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic