adding to a collections - inheritance - java

I am trying to make a project that adds cd / dvd /movie info from main() to a collections library
then prints info added.
like: output
-Book-
author: Robert A. Heinlein
# pages: 325
title: Starship Troopers
keywords: science fiction, war, weapons
-Music-
band: five finger death punch
# songs: 15
members: Zoltan Bathory, Ivan Moody,Jeremy Spencer,Matt Snell,Jason Hook
title: War is the answer
keywords: rock
I currently have 6 classes
1.project1 - main()
2.Library - where im adding to database
3.item - inheritance(title & number)
4.cd
5.dvd
6.movie
i am trying to use inheritance so i want to keep the files i have.
My question is i am trying to add to the collections in the library class. I am just not sure how to do it.
here is the classes i think you will need to see..
import java.io.PrintStream;
import java.util.Collection;
public class project
{
private static Library library = new Library();
public static void main(String[] args)
{
PrintStream out = System.out; // we will be printing to the standard output stream
Item item;
// add items to library
out.println(">>> adding items to library:\n");
item = library.addBook("The Curious Incident of the Dog in the Night-Time", "Mark Haddon", 240, "autism", "Asperger's Syndrome");
if (item != null)
library.printItem(out, item);
item = library.addBook("Starship Troopers", "Robert A. Heinlein", 325, "science fiction", "war", "weapons");
if (item != null)
library.printItem(out, item);
item = library.addBook("The Moon Is A Harsh Mistress", "Robert A. Heinlein", 389, "science fiction", "moon", "social structures");
if (item != null)
library.printItem(out, item);
item = library.addMusicCD("Europe In '72", "Grateful Dead", 12, "acid rock", "sixties", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Bill Kreutzman", "Keith Godcheaux");
library.printItem(out, item);
}
item = library.addMusicCD("Don't Let Go", "Jerry Garcia Band", 15, "acid rock", "jam bands");
if (item != null) {
library.addBandMembers(item, "Jerry Garcia", "Keith Godcheaux");
library.printItem(out, item);
}
item = library.addMusicCD("Sergeant Pepper's Lonely Hearts Club Band", "Beatles", 10, "acid rock", "sixties");
if (item != null) {
library.addBandMembers(item, "John Lennon", "George Harrison", "Ringo Starr");
library.printItem(out, item);
}
item = library.addMovieDVD("Lost In Translation", "Sofia Coppola", 14, "Japan", "loneliness");
if (item != null) {
library.addCast(item, "Bill Murray", "Scarlett Johansson");
library.printItem(out, item);
}
item = library.addMovieDVD("Groundhog Day", "Harold Ramis", 14, "newscaster", "groundhog", "time");
if (item != null) {
library.addCast(item, "Bill Murray", "Andie MacDowell");
library.printItem(out, item);
}
// print books, musicCDs, movies
out.println(">>> books:\n");
printItems(out, library.books());
out.println(">>> music CDs:\n");
printItems(out, library.musicCDs());
out.println(">>> movies:\n");
printItems(out, library.movies());
// print items for keyword
printItemsForKeyword(out, "science fiction");
printItemsForKeyword(out, "jam bands");
printItemsForKeyword(out, "xxx");
// items by artist
out.println(">>> books by Robert A. Heinlein:\n");
printItems(out, library.booksByAuthor("Robert A. Heinlein"));
out.println(">>> music by the Grateful Dead:\n");
printItems(out, library.musicByBand("Grateful Dead"));
out.println(">>> music by the Rolling Stones:\n");
printItems(out, library.musicByBand("Rolling Stones"));
out.println(">>> movies by Sofia Coppola:\n");
printItems(out, library.moviesByDirector("Sofia Coppola"));
out.println(">>> music by Jerry Garcia:\n");
printItems(out, library.musicByMusician("Jerry Garcia"));
out.println(">>> movies with Bill Murray:\n");
printItems(out, library.moviesByActor("Bill Murray"));
}
private static void printItemsForKeyword (PrintStream out, String keyword)
{
Collection<Item> items;
out.printf(">>> items for keyword: %s\n\n", keyword);
items = library.itemsForKeyword(keyword);
printItems(out, items);
}
private static void printItems (PrintStream out, Collection<Item> items)
{
if (items != null && items.size() > 0)
for (Item item : items)
library.printItem(out, item);
else
out.println("none\n");
}
}
here is the library class where i am having trouble adding to the collections..
How would i add a book or a cd to the collections?
import java.io.PrintStream;
import java.util.Collection;
import java.util.*;
public class Library
{
// returns all of the items which have the specified keyword
public Collection<Item> itemsForKeyword(String keyword)
{
return null;
}
// print an item from this library to the output stream provided
public void printItem(PrintStream out, Item item)
{
}
// adds a book to the library
public Item addBook(String title, String author, int nPages, String... keywords)
{
return null;
}
// returns all of the books by the specified author
public Collection<Item> booksByAuthor(String author)
{
return null;
}
// returns all of the books in the library
public Collection<Item> books()
{
return null;
}
// music-related methods
// adds a music CD to the library
public Item addMusicCD(String title, String band, int nSongs, String... keywords)
{
Collection MusicCollection = new HashSet();
MusicCollection.add(title);
return null;
}
// adds the specified band members to a music CD
public void addBandMembers(Item musicCD, String... members)
{
}
// returns all of the music CDs by the specified band
public Collection<Item> musicByBand(String band)
{
return null;
}
// returns all of the music CDs by the specified musician
public Collection<Item> musicByMusician(String musician)
{
return null;
}
// returns all of the music CDs in the library
public Collection<Item> musicCDs()
{
return null;
}
// movie-related methods
// adds a movie to the library
public Item addMovieDVD(String title, String director, int nScenes, String... keywords)
{
return null;
}
// adds the specified actors to a movie
public void addCast(Item movie, String... members)
{
}
// returns all of the movies by the specified director
public Collection<Item> moviesByDirector(String director)
{
return null;
}
// returns all of the movies by the specified actor
public Collection<Item> moviesByActor(String actor)
{
return null;
}
// returns all of the movies in the library
public Collection<Item> movies()
{
return null;
}
}
here is the items class
import java.io.PrintStream;
import java.util.Collection;
import java.util.*;
public class Item
{
private String title;
private int number;
public Item(String theTitle, int theNumber)
{
number = theNumber;
title = theTitle;
}
public String getTitle()
{
return title;
}
public int getNumber()
{
return number;
}
}
here is the cd class - the dvd class is almost identical
import java.util.*;
public class CD extends Item
{
private String artist;
private String members;
public CD(String theTitle, String theArtist, String theMembers, int number)
{
super(theTitle,number);
artist = theArtist;
members = theMembers;
}
public String getArtist()
{
return artist;
}
public String getMembers()
{
return members;
}
public void print()
{
System.out.println("-Music-");
System.out.println("band: " + artist);
}
}
I am not sure if i could combine the cd/dvd/movie classes into items class?
My main QUESTION is:
how should i add each cd/dvd to collections?????
in the library class
would i just define a collection to add in every addfunction(addMusicCD,addBandMembers,addMovieDVD,etc..) or should i put the collection in the beginning of the class? and how do i add to that collection???
public Item addMusicCD(String title, String band, int nSongs, String... keywords)
{
Collection MusicCollection = new HashSet(); // how should i add each cd/dvd to collections?????
MusicCollection.add(title);
return null;
}
I am also trying to return an Item and cannot! what item would i need to return??
I know this is alot of information. Sorry.
Hopefully someone can help me and not just make fun of me. i am trying to learn java from c++
Thank you for any help you can give me..

I think you need to study Object Orientation Principles a bit more.
The Library should be able to add Items. The Library methods addBook(many params) and addDVD() etc should be replaced by a more generic addItem(Item item, String... keywords).
Items can be CDs, DVDs or Movies. It's up the the CD class to add band members, not the Library class.
Adding an item to the library becomes something like
CD cd = new CD("Europe In '72", "Grateful Dead", 12);
cd.addBandMembers("Jerry Garcia", "Bill Kreutzman", "Keith Godcheaux");
library.addItem(cd, "acid rock", "sixties", "jam bands"));
Hope this helps a little to get you on track.

In addMusicCD, do a new CD(the various bits).
Add the resulting CD to the collection.
Return it.
It might be easier for you to fit this all together if you used Generics to declare collections, e.g.
class Library {
private Set<CD> theCDs;
public Item addCD(String title) {
CD cd = new CD(title);
theCDS.add(cd);
return cd;
}
}
etc, etc. etc.

I would probably add another tree of inheritance, so a Library is an abstract subclass of e.g. HashSet:
public abstract class Library<T extends Item> extends HashSet<T>{
...
abstract void addItem(T item);
}
Then you create all your libraries by subclassing your Library-class:
public class CDLibrary extends Library<Cd>{
...
#Override
public void addItem(Cd item){
// Maybe add some information of cd to a hashmap for lookups, or whatever
...
this.add(item);
}
When you're subclassing HashSet, all the add and delete operations are done for you.
If you dont need specific add-methods for each Item, you can simply remove the abstract mathod of Library, and just take advantage of the generic-syntax, to specify a new type of library when subclassing.
You might consider subclassing ArrayList, or something similar instead, as HashSet does not have a get() method, which ArrayList does, the above code was just an example of what you could do.
If its unclear, I'll try to clarify a bit more! But I hope you get the picture - subclassing to inherit the functions you need, instead of creating them again. Generics, (do you know generics?) are to ensure type-safety, so you cannot add a DVD to a CDLibrary.
Also, be sure to override equals() and hashcode() of your Items, to make sure you can distinguish between two Items.
I hope it makes sense!

Do you need to have the CDs, DVDs, and Books into separate data structures? What's your use case? If you need to get them in a separate way, then having different data structures is OK.
Otherwise, and I think this is the case, I think you could be fine having a Set<Item> and dump all your items in it.
public static class Library{
private Set<Item> items = new HashSet<Item>();
public void add(Item i){
items.add(i);
}
public String toString(){
return items.toString()
}
}
And, in your Item sub-classes, you have to have toString() overridden, and everything will print itself just fine.

Related

Object + List of Objects in a List?

I've got an interesting and troublesome task to solve.
I need to create a playlist (some kind of list) that contains songs and other sub-playlists of songs... Each playlist has a playing mode (random, sequence, etc.) Is it possible to create such playlist?
I thought about cracking the sub-playlists and adding extraxted songs from it to the master playlist or creating a sub-playlist for every song that is added to master playlist (I don't really like this idea)
Somehow it gets around the problem however it is necessary to remain playing mode of each playlist...
For example:
Master playlist(sequence palymode) has:
(1) song1-1/
(2) subplaylist(song2-1, song2-2, song-2-3) with random playmode/
(3) song1-2
The desired outcome:
(1) song1-1/
(2) song2-3 (starting random subplaylist)/
(3) song2-1/
(4) song2-2/
(5) song1-2/
how should I approach this?
Since I suspect that this is some sort of homework, I will only provide you with a partial implementation, so you get an idea how to proceed.
Create an abstract class PlaylistElement, which can later either be a Song or another Playlist.
abstract class PlaylistElement {
public abstract List<Song> printSongs();
}
Implement a class Playlist extending PlaylistElement.
class Playlist extends PlaylistElement {
private List<PlaylistElement> elements;
private PlaybackMode playbackMode;
#Override
public List<Song> printSongs() {
if(this.playbackMode == PlaybackMode.RANDOM) {
List<Song> songs = new ArrayList<>();
List<PlaylistElement> shuffleElements = new ArrayList<>();
//Add all PlaylistElements from elements into shuffleElements
//and shuffle the shuffleElements collection
//insert your songs into the songs collection here by sequentially
//going through your
//PlaylistElements and inserting the result of their printSongs()
//implementation (e.g. in a for-loop)
return songs;
}
else if(this.playbackMode == PlaybackMode.SEQUENTIAL) {
//you can do this on your own
}
return null;
}
}
Implement a class Song extending PlaylistElement.
class Song extends PlaylistElement {
private String title;
private String artist;
.
.
.
#Override
public List<Song> printSongs() {
//return a List with only this Song instance inside
return Arrays.asList(new Song[] { this });
}
}
Create an enum for your Playlist Playback Modes.
enum PlaybackMode {
SEQUENTIAL, RANDOM;
}
Hope this gives you a general idea! Getters/Setters and other important parts omitted for brevity.
Altough there are already some answers, i promised to provide a sample implementation. Starting of we have a common interface Playable which is the class to be implemented for the composite design pattern.
public interface Playable {
String getSongName();
}
Next, the Song class to represent a single song.
public class Song implements Playable {
private String name;
public Song(String name) {
this.name = name;
}
#Override
public String getSongName() {
return name;
}
}
In preparation for the Playlist class an enum to represent the difference playing modes.
public enum PlayingMode {
SEQUENCE, RANDOM
}
Now, finally the playlist class.
public class Playlist implements Playable {
private String name;
private List<Playable> playables = new ArrayList<>();
private PlayingMode mode;
private Playable currentItem;
private List<Playable> next = new ArrayList<>();
public Playlist(String name, PlayingMode mode) {
this.name = name;
this.mode = mode;
}
#Override
public String getSongName() {
if (playables.isEmpty()) {
return null;
}
if (currentItem == null) {
// initialize the playing songs
next.addAll(playables);
if (mode == PlayingMode.RANDOM) {
Collections.shuffle(next);
}
currentItem = next.get(0);
} else {
// if we have a playlist, play its songs first
if (currentItem instanceof Playlist) {
String candidate = currentItem.getSongName();
if (candidate != null) {
return candidate;
}
}
int index = next.indexOf(currentItem);
index++;
if (index < next.size()) {
currentItem = next.get(index);
} else {
currentItem = null;
}
}
return currentItem != null ? currentItem.getSongName() : null;
}
private void addToNext(Playable playable) {
if (currentItem == null) {
return;
}
// if the playlist is playing, add it to those list as well
if (mode == PlayingMode.SEQUENCE) {
next.add(playable);
} else if (mode == PlayingMode.RANDOM) {
int currentIndex = next.indexOf(currentItem);
int random = ThreadLocalRandom.current().nextInt(currentIndex, next.size());
next.add(random, playable);
}
}
public void addPlayable(Playable playable) {
Objects.requireNonNull(playable);
playables.add(playable);
addToNext(playable);
}
}
Some examples:
public static void main(String[] args) {
Song song1 = new Song("Song 1");
Song song2 = new Song("Song 2");
Playlist subPlaylist1 = new Playlist("Playlist 1", PlayingMode.RANDOM);
subPlaylist1.addPlayable(new Song("Song A"));
subPlaylist1.addPlayable(new Song("Song B"));
subPlaylist1.addPlayable(new Song("Song C"));
Song song3 = new Song("Song 3");
Playlist main = new Playlist("Main", PlayingMode.SEQUENCE);
main.addPlayable(song1);
main.addPlayable(song2);
main.addPlayable(subPlaylist1);
main.addPlayable(song3);
String songName = main.getSongName();
while (songName != null) {
System.out.println("Current song is: " + songName);
songName = main.getSongName();
}
}
Could give the output:
Current song is: Song 1
Current song is: Song 2
Current song is: Song B
Current song is: Song A
Current song is: Song C
Current song is: Song 3
You can also add songs while playing:
while (songName != null) {
System.out.println("Current song is: " + songName);
songName = main.getSongName();
// add songs while playing
if ("Song A".equals(songName)) {
subPlaylist1.addPlayable(new Song("Song D"));
subPlaylist1.addPlayable(new Song("Song E"));
subPlaylist1.addPlayable(new Song("Song F"));
}
}
This could lead to:
Current song is: Song 1
Current song is: Song 2
Current song is: Song B
Current song is: Song A
Current song is: Song E
Current song is: Song D
Current song is: Song F
Current song is: Song C
Current song is: Song 3
Some final notes:
The getIndex method does have a worst case runtime of O(n), which can be an issue if there are many songs in the playlist. A faster Collection like Set or Map will give better performace, but the implementation is a bit more complex.
The classes have been simplified, which means some getters and setters as well as equals and hashCode have been omitted for brevity.
Approach 1:
Create a class named playlist and playlist item which can hold list of songIds, which can hold set of songs from different playlists or song ids.
class PlayList{
List<PlayListItem> playlistItems;
}
class PlayListItem{
List<String> songIds;
}
This helps if a particular if you want to identify the set of songs added via a particular sub playlist. However this approach makes the iteration little difficult compared to approach 2
Approach 2:
Here the list is avoided in playlist item, so that iteration while displaying playlist is simple. However to identify the list of songIds that was added via a particularSubPlaylist has to be computed.
class PlayList{
List<PlayListItem> playlistItems;
}
class PlayListItem{
String songId;
String referencePlayListId;
}

How to remove duplication?

//Represents list books command for biblioteca
public class ListBooksCommand implements Command {
private static final String BOOKS = "Books::";
private static final String FORMAT = "%-35s %-35s %-35s";
private static final String HEADER = String.format(FORMAT, "Name", "Author", "YearPublished");
private static final String NO_BOOKS_AVAILABLE = "No Books Available";
private final Biblioteca biblioteca;
private final IO io;
public ListBooksCommand(Biblioteca biblioteca, IO io) {
this.biblioteca = biblioteca;
this.io = io;
}
#Override
public void execute() {
if (this.biblioteca.isEmpty(Book.class)) {
this.io.println(NO_BOOKS_AVAILABLE);
return;
}
this.displayBooks();
}
private void displayBooks() {
this.io.println(BOOKS);
this.io.println(HEADER);
this.io.println(this.biblioteca.representationOfAllLibraryItems(Book.class));
}
}
public class ListMoviesCommand implements Command {
private static final String Movies = "Movies::";
private static final String FORMAT = "%-35s %-35s %-35s";
private static final String HEADER = String.format(FORMAT, "Name", "Director", "YearPublished");
private static final String NO_BOOKS_AVAILABLE = "No Movies Available";
private final Biblioteca biblioteca;
private final IO io;
public ListBooksCommand(Biblioteca biblioteca, IO io) {
this.biblioteca = biblioteca;
this.io = io;
}
#Override
public void execute() {
if (this.biblioteca.isEmpty(Movie.class)) {
this.io.println(NO_MOVIES_AVAILABLE);
return;
}
this.displayMovies();
}
private void displayMovies() {
this.io.println(MOVIES);
this.io.println(HEADER);
this.io.println(this.biblioteca.representationOfAllLibraryItems(MOVIE.class));
}
}
I have two classes here one is listbooks command , listmovies command both acts on biblioteca. Both Book and Movie is of type LibraryItem(interface).
Both below codes are same. Both will ask biblioteca to get the representation of its own type. And both commands will display the representation.
This is biblioteca implementation
//Represents a library
public class Biblioteca {
private final List<LibraryItem> allLibraryItems;
public String representationOfAllLibraryItems(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems
.stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.map(LibraryItem::representation)
.collect(Collectors.joining(LINE_SEPARATOR));
}
public boolean isEmpty(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems.stream().noneMatch(libraryItem -> libraryItem.getClass().equals(itemType));
}
}
Please suggest me a pattern to avoid duplication.
Note: I'm not aware about your requirements. I'm just proposing some general design observations in this answer.
Observation 1: Biblioteca being a library, has library items. In your case, the items in the library are Movie items and Book items. So the library has two main types of items (or it can even contain more. Doesn't matter). Hence the member of Biblioteca should be:
private HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems;
A map that has item type as Key and List<LibraryItem> as value.
Biblioteca should also contain querying methods that will return the representations for a given item type and representations for all item types. So in my view, Biblioteca class should look like this:
public class Biblioteca {
private HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems;
public Biblioteca(HashMap<Class<? extends LibraryItem>, List<LibraryItem>> libraryItems) {
this.libraryItems = libraryItems;
}
/*
* Representation of a given type
*/
public String representationOfLibraryItemType(Class<? extends LibraryItem> itemType) {
if(libraryItems.containsKey(itemType)) {
return libraryItems.get(itemType).stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.map(LibraryItem::representation)
.collect(Collectors.joining(System.lineSeparator()));
} else {
throw new IllegalArgumentException("Missing type " + itemType.getSimpleName());
}
}
/*
* Representation of all types
*/
public List<String> representationOfAllLibraryItems() {
return libraryItems.values()
.stream()
.flatMap(list -> list.stream()
.map(LibraryItem::representation))
.collect(Collectors.toList());
}
}
The method representationOfLibraryItemType should be taking in a Class of item type for filtering. If the item type is found in the library, return it's representations or else throw an exception saying it's an unknown item type.
On the other hand, representationOfAllLibraryItems() should not take any input parameters. It should return all the available representations in the library.
Observation 2: Your LibraryItem should be an abstract class and each of the items in your library should extend this particular class. Because Movie is-a LibraryItem and Book is-a LibraryItem. Now, each of your items can override representation() method which is an abstract method in LibraryItem. Your LibraryItem class should look something like this:
public abstract class LibraryItem {
abstract String representation();
}
Observation 3: Your Book and Movie classes should be independent of Biblioteca because they are just items in-a Library. Today they are in a library called Biblioteca and tomorrow they can be in a library called CentralHallLibrary. So, your item class should be looking something like this:
/*
* Book Item
*/
public class Book extends LibraryItem {
private String title;
private String author;
private String publishedYear;
public Book(String title, String author, String publishedYear) {
this.title = title;
this.author = author;
this.publishedYear = publishedYear;
}
#Override
public String representation() {
/*
* I'm just returning a call to toString
* from this method. You can replace it
* with your representation logic.
*/
return toString();
}
#Override
public String toString() {
return "Book [title=" + title + ", author=" + author + ", publishedYear=" + publishedYear + "]";
}
}
/*
* Movie Item
*/
public class Movie extends LibraryItem {
private String title;
private String director;
private String releaseYear;
public Movie(String title, String director, String releaseYear) {
this.title = title;
this.director = director;
this.releaseYear = releaseYear;
}
#Override
public String representation() {
/*
* I'm just returning a call to toString
* from this method. You can replace it
* with your representation logic.
*/
return toString();
}
#Override
public String toString() {
return "Movie [title=" + title + ", director=" + director + ", releaseYear=" + releaseYear + "]";
}
}
Observation 4: I didn't find any use of the Command class which you are using. Because, as I see, your Command class has only one method called execute() that is used for displaying the representations. Generally I would put such "displaying" code in my client side (UI). If Command class has no other functions other than only printing stuff, it's not necessary in my opinion.
Testing the design: Let's create few Book items and few Movie items and then add those to the Biblioteca library
Book effJava = new Book("Effective Java", "Josh Bloch", "2008");
Book cloudNativeJava = new Book("Cloud Native Java", "Josh Long", "2017");
Book java9modularity = new Book("Java 9 Modularity", "Paul Bakker", "2017");
Movie gotgV2 = new Movie("Guardians of the Galaxy Vol. 2", "James Gunn", "2017");
Movie wonderWoman = new Movie("Wonder Woman", "Patty Jenkins", "2017");
Movie spiderHomeCmg = new Movie("Spider-man Homecoming", "Jon Watts", "2017");
List<LibraryItem> bookItems = new ArrayList<>();
List<LibraryItem> movieItems = new ArrayList<>();
bookItems.add(java9modularity);
movieItems.add(spiderHomeCmg);
bookItems.add(cloudNativeJava);
movieItems.add(wonderWoman);
bookItems.add(effJava);
movieItems.add(gotgV2);
HashMap<Class<? extends LibraryItem>, List<LibraryItem>> store = new HashMap<>();
store.put(Movie.class, movieItems);
store.put(Book.class, bookItems);
//CREATE STORE
Biblioteca bibloiteca = new Biblioteca(store);
Now, on querying the library for all representations -
List<String> allLibraryItemsRep = bibloiteca.representationOfAllLibraryItems();
Will return a result having both Movie and Book representations.
On querying the library for specific item types -
String movieRep = bibloiteca.representationOfLibraryItemType(Movie.class);
String bookRep = bibloiteca.representationOfLibraryItemType(Book.class);
Will return specific representations -
Movie [title=Spider-man Homecoming, director=Jon Watts, releaseYear=2017]
Movie [title=Wonder Woman, director=Patty Jenkins, releaseYear=2017]
Movie [title=Guardians of the Galaxy Vol. 2, director=James Gunn, releaseYear=2017]
Book [title=Java 9 Modularity, author=Paul Bakker, publishedYear=2017]
Book [title=Cloud Native Java, author=Josh Long, publishedYear=2017]
Book [title=Effective Java, author=Josh Bloch, publishedYear=2008]
On querying the library for the type which is not present in the library -
String carRep = bibloiteca.representationOfLibraryItemType(Car.class);
Will throw an exception -
java.lang.IllegalArgumentException: Missing type Car
I understand that this is quite a lengthy answer and hope this brought some clarity about the design.
You can create a generic class ListItemsCommand which will accept the item name or class as a parameter for listing and checking for empty list.
And then call ListItemsCommand with the item type like Movie or Book
If you want to remove duplication I suggest using a collect with groupingBy. This allows you to specify which is the key used for deduplication (or grouping) and a reduction function which in case of a duplicate selects the element which is to be selected from the set of duplicates.
Here is a sample method with the groupingBy collector:
public String representationOfAllLibraryItems(Class<? extends LibraryItem> itemType) {
return this.allLibraryItems
.stream()
.filter(libraryItem -> libraryItem.getClass().equals(itemType))
.collect(Collectors.groupingBy(LibraryItem::getName, LinkedHashMap::new,
Collectors.reducing((o1, o2) -> o1.toString().compareTo(o2.toString()) < 0 ? o1 : o2)))
.values()
.stream()
.map(Optional::get)
.map(LibraryItem::representation)
.collect(Collectors.joining(LINE_SEPARATOR));
}
Here is a small test in which we de-duplicate by name of the movie and select the most recent entry in the data:
public static void main(String[] args) {
List<LibraryItem> items = Arrays.asList(new Movie("Valerian", "Luc Besson", "2017"),
new Movie("Valerian", "Luc Besson", "2016"),
new Movie("Spiderman", "Sam Raimi", "2002"),
new Movie("Spiderman", "Sam Raimi", "2001"),
new Movie("Spiderman", "Sam Raimi", "2003"));
Biblioteca biblioteca = new Biblioteca(items);
System.out.println(biblioteca.representationOfAllLibraryItems(Movie.class));
}
The result looks like this:
Luc Besson - Valerian - 2017
Sam Raimi - Spiderman - 2003
Here the de-duplication happens by movie name and the most recent movie is selected.

Generalizing a searching method between ArrayLists of classes

I have a four classes Book Disk Paper Magazine all of them derive from another class Items and all of them have a String barcode field.
In another class foo I have ArrayList<Book> books; ArrayList<Disk> disks; ArrayList<Paper> papers; ArrayList<Magazine> magazines;, and I want to implement for each one of these a getByBarcode(String barcode) method, that would look in the arraylist for the item with that barcode. If it's a book it has to look in the books list etc.
Can I avoid having to do four different ones? What I mean is avoiding having to do a getBookByBarcode(String barcode) that would have to look in the books list, getDiskByBarcode(String barcode) that would have to look in the disks list etc..
And have a generic one like public Object getByBarcode(String barcode,type). How do I do this nicely in an OOP way?
Essentially every Book, Magazine, Disk & Paper is an Item. Hence you should have a parent class named Item and not its plural form. Every Base Class should classify as a singular entity.
You should then create objects of Book, Magazine, Disk & Paper. Since all of these classify as an Item, create an array list of type Item and add these objects to the same.
This way you have a item list which has books, magazines, disks & papers. You can then look into this list for an item with barcode and get the type of item.
Source Code:
Item.java
package myLibrary;
public class Item {
protected String barcode;
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public Item(String barcode) {
this.barcode = barcode;
}
}
Book.java / Disk.java / Magazine.java / Paper.java
package myLibrary;
public class Book extends Item {
public Book(String barcode) {
super(barcode);
}
public String getBarcode() {
return barcode;
}
}
Lecturer.java (Class containing main function)
package myCollege;
import java.util.ArrayList;
import myLibrary.Book;
import myLibrary.Disk;
import myLibrary.Item;
import myLibrary.Magazine;
import myLibrary.Paper;
public class Lecturer {
public static void main(String[] args) {
// Declare items
Book x1 = new Book("Item101");
Book x2 = new Book("Item102");
Disk x3 = new Disk("Item201");
Disk x4 = new Disk("Item202");
Magazine x5 = new Magazine("Item301");
Paper x6 = new Paper("Item401");
Paper x7 = new Paper("Item402");
ArrayList<Item> items = new ArrayList<>();
items.add(x1);
items.add(x2);
items.add(x3);
items.add(x4);
items.add(x5);
items.add(x6);
items.add(x7);
String itemType = getItemByBarcode("Item202", items);
System.out.println(itemType);
}
private static String getItemByBarcode(String barcode, ArrayList<Item> items) {
String itemType = "";
for(Item i : items) {
if(i.getBarcode().equalsIgnoreCase(barcode)) {
itemType = i.getClass().getSimpleName();
}
}
return itemType;
}
}
Output:
Disk
I hope this helps in better understanding of the concept/issue.
may sound hackish but you can do like some other users suggested and call
public Object getByBarcode(String barcode, Class<T> classy)
{
ArrayList<Items> items = null;
if(classy.class.getSimpleName().equals(Book.class.getSimpleName()))
items = bookArray;
else if(classy.class.getSimpleName().equals(Magazine.class.getSimpleName()))
items = magazineArray;
else
... cnt'd
for(Item i : items)
if( i.getBarCode().equals(barcode) return i;
}
Then to call this beastly mess you could do something like . . .
Item i = getByBarCode("0932A3", Book.class);

Java method parameter for creating new object of different class

I have searched high and low for a solution to this problem, and finally signed up here to see if someone can point me to what is undoubtedly a really simple solution that is evading me. I'm working on MIT's OpenCourse to teach myself Java and am stumped on this problem.
I have two classes, Library and Book. The program keeps track of books created for each library, their location, and whether or not they are checked out. I am given the main method for Library that cannot be edited. Instead its methods must be built to produce the desired output. The issue I am having is determining the argument syntax to pass to a method in Library that creates a new Book in the main method of Library.
Relevant Library Code:
package mitPractice;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
Book[] catalog;
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Thrones"));
firstLibrary.addBook(new Book("Rama"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Clans"));
So my question is how to make the method compatible with the code given in the main method? I have attempted numerous combinations for arguments to pass to addBook() and none seem to deliver.
Book code:
package mitPractice;
public class Book {
Boolean isCheckedOut = false;
String book_title;
public Book(String title) {
book_title = title;
}
public void Borrow() {
isCheckedOut = true;
}
public void Return() {
isCheckedOut = false;
}
public boolean isBorrowed() {
if (isCheckedOut == true) {
return true;
} else {
return false;
}
}
public String getTitle() {
return book_title;
}
/*public static void main(String[] args) {
Book example = new Book("A Game of Thrones");
System.out.println("Title: " + example.getTitle());
System.out.println("Borrowed?: " + example.isBorrowed());
example.Borrow();
System.out.println("Borrowed?: " + example.isBorrowed());
example.Return();
System.out.println("Borrowed?: " + example.isBorrowed());
}*/
}
You want the parameter to be of type Book:
public void addBook(Book newBook) {
catalog[(catalog.length + 1)] = newBook;
}
This will throw an ArrayIndexOutOfBoundsException though, because you're trying to put an element in the array after the last index. You'll need to keep track of how many books have been added and rebuild your array when it gets full. Like this:
private int numberOfBooks = 0;
public void addBook(Book newBook) {
numberOfBooks++;
if(numberOfBooks >= catalog.length) {
// Rebuild array
Book[] copy = new Book[catalog.length * 2]
for(int i=0; i<catalog.length; i++){
copy[i] = catalog[i];
}
catalog = copy;
}
catalog[numberOfBooks] = newBook;
}
Or use a collection like java.util.ArrayList.
So instead of having this line:
Book[] catalog;
You might have
ArrayList<Book> catalog = new ArrayList<Book>();
This creates an ArrayList which is a Java implementation of a dynamically sized array.
Then your addBook method might look like this:
public void addBook(Book newBook) {
catalog.add(newBook);
}
In order to use ArrayList you'll need to include this line at the beginning of the file, after the package mitPractice; line:
import java.util.ArrayList;
This always ends in array out of bounds :
public void addBook(/*unsure what parameter to add here*/) {
catalog[ (catalog.length + 1)] = //unknown parameter
}
Actually, the best would be to use List :
public class Library {
List<Book> catalog = new ArrayList<>();
...
}
Then you can simply do this :
public void addBook(Book book) {
catalog.add(book);
}
Try this code. This will add a book to a very important data structure called an ArrayList found in the util package in java. A programmer has to import this before the class statement but after any package statement. The code also uses a method from your Book API to print the title when a book is successfully added to the ArrayList. ArrayLists are favourable over Arrays because an java.util.ArrayList can expand without problems whereas an Array is a fixed size and is not so dynamic.
Check out this code I modified of the Library class that compiles and runs.
package mitPractice;
import java.util.ArrayList;
public class Library {
String library_address;
static String library_hours = "Libraries are open daily from 9AM to 5PM";
ArrayList<Book> books = new ArrayList<Book>();
//List of Methods for Libraries
public Library(String address) {
library_address = address;
}
public static void printOpeningHours() {
System.out.println(library_hours);
}
public void addBook(Book b/*unsure what parameter to add here*/) {
books.add(b); // add the book to the ArrayList
System.out.println("The book: " + b.getTitle() + " was successfully added.");
}
public static void main(String[] args) {
//Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
//Add four books ***This block of code is the problem and is uneditable
firstLibrary.addBook(new Book("A Game of Drones"));
firstLibrary.addBook(new Book("Raman Noodles"));
firstLibrary.addBook(new Book("Understanding Space"));
firstLibrary.addBook(new Book("Way of the Yoga Baywatch Babes"));
} // end main
} // end Library class
I hope this helps some.
All the best,
user_loser

Java Object Array Foreach Method Access

After developing in PHP for a long time I have decided to step into Java. Comfortable in OOP methodology and all that, I'm trying to start off at that point within java, but I'm getting hung up on passing out my arraylist object into a for statement to be printed back out using the Item class methods.
HelloInvetory.java
package helloInventory;
import java.util.Arrays;
public class HelloInventory {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
}
Inventory.java
package helloInventory;
import java.util.*;
/**
* Tracks and maintains all items within the inventory
* #author levi
*
*/
public class Inventory {
List<Object> InventoryItems = new ArrayList<Object>();
/*
* create object from Items class
* and insert into Object[] array.
*/
public void createItemObj(int sku, String name, String descriptor, float price) {
Items item = new Items();
item.setSku(sku);
item.setItemName(name);
item.setItemDescription(descriptor);
item.setItemPrice(price);
this.setInventoryItems(item);
}
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
public void setInventoryItems(Object inventoryItems) {
//InventoryItems.add(inventoryItems);
this.InventoryItems.add(inventoryItems);
}
}
Items.java
package helloInventory;
/**
* Class object to hold each item details
* #author levi
*
*/
public class Items {
int sku;
String itemName;
String itemDescription;
float itemPrice;
public int getSku() {
return sku;
}
public void setSku(int sku) {
this.sku = sku;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemDescription() {
return itemDescription;
}
public void setItemDescription(String itemDescription) {
this.itemDescription = itemDescription;
}
public float getItemPrice() {
return itemPrice;
}
public void setItemPrice(float itemPrice) {
this.itemPrice = itemPrice;
}
}
Where I am stuck is within the HelloInventory.java
for(Object item : InvetoryItems){
System.out.println(item.getItemName());
}
IDE (Eclipse) gives me the error "Can only iterate over an array or an instance of java.lang.Iterable". Is there something extra I need, or I'm I going around this totally the wrong way in Java? Correct example would be helpful.
Best,
Levi
You have a very strange architecture here my friend. You shouldn't be using generic Objects everywhere, but the actual types. First thing:
public Object getAllInventoryItems() {
//return InventoryItems;
return this.InventoryItems.toArray();
}
Why not just return the List itself?
public List<Item> getAllInventoryItems() {
return this.InventoryItems;
}
Also change this:
List<Item> InventoryItems = new ArrayList<Item>();
and this:
public void setInventoryItems(Item inventoryItems) {
this.InventoryItems.add(inventoryItems);
}
Now iterating the List is smooth sailing:
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Item> InvetoryItems;
Inventory inv = new Inventory();
inv.createItemObj(101, "camera", "Used camera that I bought off of a homeless guy.", 500);
InvetoryItems = inv.getAllInventoryItems();
for(Item item : InvetoryItems){
System.out.println(item.getItemName());
}
System.out.println("Done");
}
Btw, I changed Items to Item out of habit. A class name should indicate a single entity so by convention it's singular.
Now don't take this the wrong way, but you may have got off on the wrong foot with Java, so I highly recommend this reading: http://www.mindview.net/Books/TIJ/ This worked for me when I was starting with Java, maybe others can suggest some good sources as well.
Ok, two things. One is that Tudor is absolutely right, it's best to use the classes you're expecting directly, not Objects, and stylistically his points are accurate too.
Two is that if you really have to use a list of object, you'll need to cast back from object to whatever type it is that you're expecting to receive.
List<Object> list = inv.getAllInventoryItems();
for (Object item : list){
System.out.println((Items) item).getItemName();
}
However, I wouldn't recommend doing this as it effectively takes what should be a compile-time error and makes it a RunTime error (if the class cannot be cast).

Categories