Created
February 7, 2016 21:46
-
-
Save AnnaBoro/edb0485e9751d1410b95 to your computer and use it in GitHub Desktop.
generics + comparator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lesson7_10.generics; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.Comparator; | |
import java.util.List; | |
public class Box<T extends Bird>{ | |
private List<T> birdsList; | |
public Box() { | |
birdsList = new ArrayList<T>(); | |
} | |
public T getBird(int birdIndex) { | |
return birdsList.get(birdIndex); | |
} | |
public List<T> getBirdsList() { | |
return birdsList; | |
} | |
public void addBird(T bird) { | |
birdsList.add(bird); | |
} | |
public void removeBird(T bird) { | |
birdsList.remove(bird); | |
} | |
private class BirdsComparator implements Comparator<Bird> { | |
@Override | |
public int compare(Bird o1, Bird o2) { | |
return o1.getName().compareTo(o2.getName()); | |
} | |
} | |
public void sortBirdsByName() { | |
Collections.sort(birdsList, new BirdsComparator()); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package lesson7_10.generics; | |
public class BoxDemo { | |
public static void main(String[] args) { | |
Box<Bird> birds = new Box<Bird>(); | |
Bird bird1= new Eagle(); | |
bird1.setName("eagle"); | |
Bird bird2 = new Duck(); | |
bird2.setName("duck"); | |
Bird bird3 = new Eagle(); | |
bird3.setName("eeagle"); | |
birds.addBird(bird1); | |
birds.addBird(bird2); | |
birds.addBird(bird3); | |
for (Bird b : birds.getBirdsList()) { | |
System.out.println(b.toString()); | |
} | |
birds.sortBirdsByName(); | |
for (Bird b : birds.getBirdsList()) { | |
System.out.println(b.toString()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment