Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Taking an element out of an array

  1. #1
    Junior Member
    Join Date
    May 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Taking an element out of an array

    I'm trying to take an animal element of an array for filtering but I'm having some problems. I need to take the element i need out of the array. Then I need to find out whether the animal is the type I need. Finally I need to add the animal object to the array. I have to seperate arrays of displayed animals and all the animals but I'm just having trouble figuring out how to do the above. Any advice is greatly appreciated. Here's what I have so far:

     
     
           public void filterDogs()
          {
     
     
             Iterator i = animals.iterator();
     
             while(i.hasNext()) 
             { 
                Animal a = (Animal)i.next(); 
                if(a instanceof Dog)
                  Dog += displayedAnimals.add(a); 
             }
          }

    And the entire code:
       import javax.swing.*;  
       import java.util.ArrayList;
       import java.util.*;
       import java.util.Collections;
       import javax.swing.Timer;
     
     
        public class AnimalListDisplay extends JList
       {
          ArrayList<Animal> animals;
          ArrayList<Animal> displayedAnimals;
     
          boolean specialNeedsOnly = false;
          boolean birdsOn = false;
          boolean dogsOn = false;
          boolean catsOn = false;
     
     
           public AnimalListDisplay(ArrayList<Animal> allAnimals)
          {
     
             animals = allAnimals;
             displayedAnimals = animals;
          }
           public void addAnimal(Animal animal)
          {
             animals.add(animal);
     
             setListData(animals.toArray());
     
          }
           public void sortAge()
          {
     
             AgeCompare a1 = new AgeCompare();
             Collections.sort(displayedAnimals, a1);
             setListData(displayedAnimals.toArray());
          }
     
     
           public void sortSize()
          {
     
             Collections.sort(displayedAnimals);
             setListData(displayedAnimals.toArray());
          }
     
     
           public void filterSpecialNeeds()
          {
     
             if(specialNeedsOnly == false)
             {
                displayedAnimals = new ArrayList<Animal>();
     
                Iterator i = animals.iterator();
     
                while(i.hasNext())
                {
                   Animal a = (Animal)i.next();
                   if(a.getNeeds())
                      displayedAnimals.add(a);
                }
                setListData(displayedAnimals.toArray());
                specialNeedsOnly = true;
             }
     
             else if(specialNeedsOnly == true)
             {
     
                setListData(animals.toArray());
                specialNeedsOnly = false;
     
             }
          }
     
          // public void addAnimal(Animal pet){
            // displayedAnimals.add(pet);
            // animals.add(pet);
     
     
     
     
           public void filterDogs()
          {
     
     
             Iterator i = animals.iterator();
     
             while(i.hasNext()) 
             { 
                Animal a = (Animal)i.next(); 
                if(a instanceof Dog)
                   displayedAnimals.add(a); 
             }
          }
           public void filterCats()
          {
             if(catsOn == false)
             {
                displayedAnimals = new ArrayList<Animal>();
     
                Iterator i = animals.iterator();
     
                while(i.hasNext())
                {
                   Animal a = (Animal)i.next();
                   if(a.getNeeds())
                      displayedAnimals.add(a);
                }
                setListData(displayedAnimals.toArray());
                catsOn = true;
             }
     
             else if(catsOn == true)
             {
     
                setListData(animals.toArray());
                catsOn = false;
             }
          }
           public void filterBirds()
          {
             if(birdsOn == false)
             {
                displayedAnimals = new ArrayList<Animal>();
     
                Iterator i = animals.iterator();
     
                while(i.hasNext())
                {
                   Animal a = (Animal)i.next();
                   if(a.getNeeds())
                      displayedAnimals.add(a);
                }
                setListData(displayedAnimals.toArray());
                birdsOn = true;
             }
     
             else if(birdsOn == true)
             {
     
                setListData(animals.toArray());
                birdsOn = false;
     
             }
     
     
          }
       }


  2. #2
    Member
    Join Date
    Apr 2010
    Location
    The Hague, Netherlands
    Posts
    91
    Thanks
    3
    Thanked 10 Times in 10 Posts

    Default Re: Taking an element out of an array

    Your thinking way to difficult dude.

    public abstract class Animals
    {
    	public static final Integer CATS = 0;
    	public static final Integer DOGS = 1;
    	public static final Integer BIRDS = 2;
    	protected Hashtable<Animal> animals = new Hashtable<Animal>(); //protected!!!
     
    	public abstract Hashtable<Animal> collect(int specieType);
    	public abstract void add(Animal a);
    	public abstract Animal get(int id);
    	public abstract void edit(Animal a);
    	public abstract boolean remove(Animal a);
    }
     
    public class AnimalCollection extends Animals
    {
    	private Hashtable<Animal> collection = new Hashtable<Animal>();
     
    	public Hashtable<Animal> collect(int specieType)
    	{
    		String specie;
    		switch(specieType)
    		{
    			case 0:
    				specie = "Cat";
    			break;
    			case 1:
    				specie = "Dog";
    			break;
    			case 2:
    				specie = "Bird";
    			break;
    			default:
    				throw new Exception("Unknown type.");
    		}
     
    		Hashtable<Animal> col = new hashtable<Animal>();
    		for(Animal a : super.animals)
    		{
    			if(a instanceof specie)
    			{
    				col.put(a.hashCode(), a);
    			}
    		}
    		this.collection = col; //if you want to have the same collection some time later, you load this and dont call the method again(performance)
    		return col;
    	}
     
    	@override
    	public void add(Animal a) {}
     
    	@override
    	public Animal get(int id) {}
     
    	@override
    	public void edit(Animal a) {}
     
    	@override
    	public boolean remove(Animal a) {}
    }
     
    Call: 
    AnimalCollection aC = new AnimalCollection();
    Hashtable dogsCollection = aC.collect(Animals.DOGS);
    I made this with notepad++ so there may be some syntax errors.
    Last edited by Bryan; May 3rd, 2010 at 07:00 AM.

  3. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Taking an element out of an array

    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  4. #4
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Taking an element out of an array

    Quote Originally Posted by Bryan View Post
    public abstract class Animals
    {
    	public static final Integer CATS = 0;
    	public static final Integer DOGS = 1;
    	public static final Integer BIRDS = 2;
    	protected Hashtable<Animal> animals = new Hashtable<Animal>(); //protected!!!
     
    	public abstract Hashtable<Animal> collect(int specieType);
    	public abstract void add(Animal a);
    	public abstract Animal get(int id);
    	public abstract void edit(Animal a);
    	public abstract boolean remove(Animal a);
    }
     
    public class AnimalCollection extends Animals
    {
    	private Hashtable<Animal> collection = new Hashtable<Animal>();
     
    	public Hashtable<Animal> collect(int specieType)
    	{
    		String specie;
    		switch(specieType)
    		{
    			case 0:
    				specie = "Cat";
    			break;
    			case 1:
    				specie = "Dog";
    			break;
    			case 2:
    				specie = "Bird";
    			break;
    			default:
    				throw new Exception("Unknown type.");
    		}
     
    		Hashtable<Animal> col = new hashtable<Animal>();
    		for(Animal a : super.animals)
    		{
    			if(a instanceof specie)
    			{
    				col.put(a.hashCode(), a);
    			}
    		}
    		this.collection = col; //if you want to have the same collection some time later, you load this and dont call the method again(performance)
    		return col;
    	}
     
    	@override
    	public void add(Animal a) {}
     
    	@override
    	public Animal get(int id) {}
     
    	@override
    	public void edit(Animal a) {}
     
    	@override
    	public boolean remove(Animal a) {}
    }
     
    Call: 
    AnimalCollection aC = new AnimalCollection();
    Hashtable dogsCollection = aC.collect(Animals.DOGS);
    I made this with notepad++ so there may be some syntax errors.
    Hmm, that needs a bit more work...
    Don't forget that a Hashtable is a keyed collection, so should be declared with two generic type arguments - but a Hashtable won't work here if you want more than one instance of each species in the collection - Hashtable keys are unique.
    You could profitably replace the Integer 'specieType' with an enum.
    It would simplify things if an Animal knew its specieType - which it should.
    Should AnimalCollection really extend Animals, or does this complicate things?
    There seems little point in having a Hashtable of a single animal species, ArrayList would be more appropriate (especially if an Animal knows its Species)?

    If all that's needed is to extract a particular species from a mixed collection, wouldn't something like this be simpler:
    import java.util.ArrayList;
    import java.util.List;
     
    class AnimalFilter
    {
        public static void main(String[] args) {
            List<Animal> animals = new ArrayList<Animal>();
            animals.add(new Dog(..));
            animals.add(new Cat(..));
            animals.add(new Bird(..));
            animals.add(new Dog(..));
            animals.add(new Bird(..));
     
            AnimalFilter filter = new AnimalFilter();
            List<Animal> dogsCollection = filter.collect(animals, Animal.Species.DOGS);
            ... // do something with Dogs
        }
     
    	public List<Animal> collect(List<Animal> animals, Animal.Species species)
    	{
    		List<Animal> selectedAnimals = new ArrayList<Animal>();
    		for(Animal animal : animals)
    		{
    			if(animal.isSpecies(species)) {
    				selectedAnimals.add(animal);
    			}
    		}
    		return selectedAnimals;
    	}   
    }
     
    abstract class Animal {
        public enum Species { CATS, DOGS, BIRDS }
     
        protected Species species;
     
        public Species getSpecies() {
            return species;
        }
        public boolean isSpecies(Species s) {
            return species == s;
        }
    }
     
    class Dog extends Animal { ... }
    class Cat extends Animal { ... }
    class Bird extends Animal { ... }
    If an explicit Species type id isn't needed, you could even get rid of the Species enum and just use the Animal class type:
    class AnimalFilter
    {
        public static void main(String[] args) {
            List<Animal> animals = new ArrayList<Animal>();
            animals.add(new Dog(..));
            animals.add(new Cat(..));
            animals.add(new Bird(..));
            animals.add(new Dog(..));
            animals.add(new Bird(..));
     
            AnimalFilter filter = new AnimalFilter();
            List<Animal> dogsCollection = filter.collect(animals, Dog.class);
            ... // do something with Dogs
        }
     
    	public List<Animal> collect(List<Animal> animals, Class speciesClass)
    	{
    		List<Animal> selectedAnimals = new ArrayList<Animal>();
    		for(Animal animal : animals)
    		{
    			if(animal.getClass().equals(speciesClass)) {
    				selectedAnimals.add(animal);
    			}
    		}
    		return selectedAnimals;
    	}
    }
     
    abstract class Animal { ... }
    class Dog extends Animal { ... }
    class Cat extends Animal { ... }
    class Bird extends Animal { ... }
    YMMV.

Similar Threads

  1. how to find an element in an array
    By humdinger in forum Collections and Generics
    Replies: 8
    Last Post: April 9th, 2010, 05:22 PM
  2. new arrayList element overwrites all previous
    By twinkletoes in forum Object Oriented Programming
    Replies: 2
    Last Post: April 2nd, 2010, 07:45 AM
  3. Add white spices before the String element
    By bookface in forum Java Theory & Questions
    Replies: 1
    Last Post: March 23rd, 2010, 08:50 PM
  4. [SOLVED] theory behind testing each element of an array.
    By etidd in forum Java Theory & Questions
    Replies: 2
    Last Post: February 5th, 2010, 09:04 AM
  5. How to extract a particular element details which has more references ???
    By j_kathiresan in forum Algorithms & Recursion
    Replies: 1
    Last Post: December 31st, 2009, 01:11 AM