I'm trying to optimize a section of my code which requires an object array with constructor parameters in it. Is there a way to add that to the arguments of a method?
I have an array of objects called SongList in that array there are objects from the Song Class with constructor parameters:
songs[] songList = new songs[1];
songList[0] = new songs("Danger Zone", "danger zone.mp3", "Kenny Loggins", 3.33);
I also have a method that searches the array based on the category and the search query:
//Method
public static songs[] search(songs SearchCategory , String Quarry){}
//Calling of method
search = AudioPlayer.search("aName", "Kenny Loggins");
Songs class:
public class songs {
String sName;
String fPath;
String aName;
double sLength;
public songs(String songName,
String filePath,
String Artist,
double songLength) {
sName = songName;
fPath = filePath;
aName = Artist;
sLength = songLength;
}
}
Is there a way I could make the first argument of the code accept a constructor parameter like Name? This would allow me to cut down the overall length of my code as I wouldn't need to use a switch statement.
Search method:
public static songs[] search(String SearchCategory , String Quarry){
//Returned array value
songs[] ReturnedResult = new songs[0];
// Method only list
List<songs> SearchResult = new ArrayList<songs>();
switch (SearchCategory) {
case "aName":
//for loop looks through all objects with the SearchCategory and places any found values into the list
for (songs songs : AudioListing) {
if (songs.aName.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "sName":
for (songs songs : AudioListing) {
if (songs.sName.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "fPath":
for (songs songs : AudioListing) {
if (songs.fPath.equals(Quarry)) {
SearchResult.add(songs);
}
}
case "sLength":
//Since the given quarry is a string and the length is a double the quarry is converted
double QuarryDoubleTypeC = Double.parseDouble(Quarry);
for (songs songs : AudioListing) {
if (songs.sLength == QuarryDoubleTypeC) {
SearchResult.add(songs);
}
}
}
// Conversion of list to array for ease of use
ReturnedResult = SearchResult.toArray(ReturnedResult);
return ReturnedResult;
}
There is a concept of reflection in Java that you can use here.
You can use the SearchCategory to get the field value from the object
Then you can use it to compare with Quarry
The working code is as below
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Songs {
String sName;
String fPath;
String aName;
double sLength;
static Songs[] AudioListing = new Songs[1];
static {
AudioListing[0] = new Songs("Danger Zone", "danger zone.mp3", "Kenny Loggins", 3.33);
}
public Songs(String songName, String filePath, String Artist, double songLength) {
sName = songName;
fPath = filePath;
aName = Artist;
sLength = songLength;
}
public static Songs[] search(String SearchCategory, String Quarry) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
// Returned array value
Songs[] ReturnedResult = new Songs[0];
// Method only list
List<Songs> SearchResult = new ArrayList<Songs>();
for (Songs song : AudioListing) {
Field field = Songs.class.getDeclaredField(SearchCategory);
String fieldValue = (String) field.get(song);
if (fieldValue.equals(Quarry)) {
SearchResult.add(song);
}
}
// Conversion of list to array for ease of use
ReturnedResult = SearchResult.toArray(ReturnedResult);
return ReturnedResult;
}
#Override
public String toString() {
return "Songs [sName=" + sName + ", fPath=" + fPath + ", aName=" + aName + ", sLength=" + sLength + "]";
}
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//Calling of method
Songs[] results = Songs.search("aName", "Kenny Loggins");
System.out.println(Arrays.toString(results));
}
}
This explains how it can be achieved you can further enhance your code after further exploring in this direction.
This is an excellent opportunity to leverage higher-order functions.
In Java, these are realized via Functional Interfaces.
You can reference the methods -- or fields -- from your Song class (which should be capitalized and singular, not songs) itself via Songs::aName. Furthermore, if you are trying to find a value, leveraging Predicate<Song> is an excellent idea.
Also, using Collections instead of arrays is advisable.
In short, your code could easily look like this:
class AudioPlayer {
List<Song> audioListings = new ArrayList<>();
public void add(Song song) { audioListings.add(song); }
public List<Song> search(Predicate<Song> predicate) {
return audioListings.stream()
.find(predicate)
.collect(Collectors.toList());
}
}
You would then use it like this:
AudioPlayer player = new AudioPlayer();
// fill with songs
player.add(new Song("Danger Zone", "danger zone.mp3", "Kenny Loggins", 3.33));
// find song with a specific aName
var songs = player.search(song => song.aName.equals("Kenny Loggins"));
The added benefit is that you can search for very complex things by constructing more complex predicates:
// find song with specific aName AND shorter then a given length
Predicate<Song> query =
song => song.aName.equals("Kenny Loggins")
.and(song => song.sLength <= 3.5);
var songs = player.search(query);
I would advise against using reflection for this. Reflection comes with a whole range of problems and it simply isn't needed. The approach I have outlined above is far more idiomatic Java since Java 8, scales better, is easier to read, less error-prone and overall cleaner.
What you're looking for is a bit advanced; it's the interface Function<Song, String>. This will allow you to provide some transformation that selects a string value for your Song object, particularly in this case such options as Song::getSName. This is how it would be done with streams (and collections):
songList.stream()
.filter(song -> quarry.equals(function.apply(song)))
.findAll();
However, I strongly recommend that you become more familiar with the basics of Java before diving into more complicated logic, especially standards about naming (classes should be capitalized; variables should not), collections (lists are usually preferred over arrays), static vs. instance members, and interfaces.
Related
I don't know if this is possible in Java but I was wondering if it is possible to use an object in Java to return multiple values without using a class.
Normally when I want to do this in Java I would use the following
public class myScript {
public static void main(String[] args) {
// initialize object class
cl_Object lo_Object = new cl_Object(0, null);
// populate object with data
lo_Object = lo_Object.create(1, "test01");
System.out.println(lo_Object.cl_idno + " - " + lo_Object.cl_desc);
//
// code to utilize data here
//
// populate object with different data
lo_Object = lo_Object.create(2, "test02");
System.out.println(lo_Object.cl_idno + " - " + lo_Object.cl_desc);
//
// code to utilize data here
//
}
}
// the way I would like to use (even though it's terrible)
class cl_Object {
int cl_idno = 0;
String cl_desc = null;
String cl_var01 = null;
String cl_var02 = null;
public cl_Object(int lv_idno, String lv_desc) {
cl_idno = lv_idno;
cl_desc = lv_desc;
cl_var01 = "var 01";
cl_var02 = "var 02";
}
public cl_Object create(int lv_idno, String lv_desc) {
cl_Object lo_Object = new cl_Object(lv_idno, lv_desc);
return lo_Object;
}
}
// the way I don't really like using because they get terribly long
class Example {
int idno = 0;
String desc = null;
String var01 = null;
String var02 = null;
public void set(int idno, String desc) {
this.idno = idno;
this.desc = desc;
var01 = "var 01";
var02 = "var 02";
}
public int idno() {
return idno;
}
public String desc() {
return desc;
}
public String var01() {
return var01;
}
public String var02() {
return var02;
}
}
Which seems like a lot of work considering in Javascript (I know they are different) I can achieve the same effect just doing
var lo_Object = f_Object();
console.log(lo_Object["idno"] + " - " + lo_Object[desc]);
function f_Object() {
var lo_Object = {};
lo_Object = {};
lo_Object["idno"] = 1;
lo_Object["desc"] = "test01";
return lo_Object;
}
NOTE
I know the naming convention is wrong but it is intentional because I have an informix-4gl program that runs with this program so the coding standards are from the company I work for
The best way to do this is to use HashMap<String, Object>
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, Object> person =
new HashMap<String, Object>();
// add elements dynamically
person.put("name", "Lem");
person.put("age", 46);
person.put("gender", 'M');
// prints the name value
System.out.println(person.get("name"));
// asures that age element is of integer type before
// printing
System.out.println((int)person.get("age"));
// prints the gender value
System.out.println(person.get("gender"));
// prints the person object {gender=M, name=Lem, age=46}
System.out.println(person);
}
}
The advantage of doing this is that you can add elements as you go.
The downside of this is that you will lose type safety like in the case of the age. Making sure that age is always an integer has a cost. So to avoid this cost just use a class.
No, there is no such a feature, you have to type out the full type name(class name).
Or use may use val :
https://projectlombok.org/features/val.html
Also, if you use IntelliJ IDEA
try this plugin :
https://bitbucket.org/balpha/varsity/wiki/Home
I am not sure if it's possible with Java. Class is the primitive structure to generate Object. We need a Class to generate object. So, for the above code, i don't think there is a solution.
Java methods only allow one return value. If you want to return multiple objects/values consider returning one of the collections. Map, List, Queue, etc.
The one you choose will depend on your needs. For example, if you want to store your values as key-value pairs use a Map. If you just want to store values sequentially, use a list.
An example with a list:
list<Object> myList = new ArrayList<Object>();
myList.add("Some value");
return myList;
As a side note, your method create is redundant. You should use getters and setters to populate the object, or populate it through the constructor.
cl_Object lo_Object = new cl_Object(1, "test01");
The way you have it set up right now, you're creating one object to create another of the same type that has the values you want.
Your naming convention is also wrong. Please refer to Java standard naming convention:
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
I am having issues with objects and classes.
I had to define two classes:
Course: a course has a code, an name and a number of credits
Teacher: a teacher has a first name and last name. He can be asked his full name.
So far so good, I got no issue with them, but I have to do next assignment which I was trying to do in the last 2 days and I could not find a proper answer:
Extend the code of the class teacher. A teacher also has a list of courses he can teach. Add an array of Courses to the code. Also add a function addCourse(Course aCourse) to the code. Courses can also be removed from teachers.
I could do everyting in my way but no clue on how to create the addCourse(Course aCourse) method.
Find below my coding, but it must be according to the method described:
public class Course {
private String courseCode;
private String courseName;
private String numberOfCredits;
public Course(String courseCode, String courseName, String numberOfCredits) {
super();
this.courseCode = courseCode;
this.courseName = courseName;
this.numberOfCredits = numberOfCredits;
}
public void print() {
System.out.println(courseCode + "\t" + courseName + "\t" + numberOfCredits);
}
public static void main(String[] args) {
Course[] courseArray = new Course[4];
System.out.println("Code" + "\t" + "Name" + "\t" + "Credits");
courseArray[0] = new Course("001", "Hist", "3");
courseArray[1] = new Course("002", "Phy", "3");
courseArray[2] = new Course("003", "Math", "3");
courseArray[3] = new Course("004", "Log", "3");
for (int i = 0; i < courseArray.length; i++) {
courseArray[i].print();
}
}
}
Arrays are fixed length collections of objects, so you'll need to decide how big your array should be. Let's call the length of your array MAX_COURSES. A more advanced solution might resize the array when required, but I get the impression this is beyond the scope of your course.
So you need to define the Course[] array as a field of your Teacher class. The syntax of array declarations is quite easy to research, so I won't put that in here. Just make sure your array length is equal to MAX_COURSES.
Now, to add courses to the array, you need to know where to put them. To keep track of the next free position of the array, the easiest thing to do is to declare a field in your class:
private int numCourses = 0;
Now, when you add a new course, insert the course into the index specified by numCourses. Make sure you increment numCourses after you've added the course.
Finally, you ought to test to see if your array is full before you agree to insert a new course into the array, i.e. check if numCourses is smaller than MAX_COURSES. If it's not, you need to throw an exception.
I would recommend using a collection (such as a List) rather than an array. The code would look something like:
public class Teacher {
private final String firstName;
private final String lastName;
private final List<Course> courses = new ArrayList<Course>();
public Teacher(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void addCourse(Course course) {
courses.add(course);
}
}
Based on that example, you should be able to add the removeCourse method yourself, and any other method you need to operate on the list of courses.
If you want to return the list as an array, you could always convert it, e.g:
public Course[] getCourses() {
return courses.toArray(new Course[courses.size()]);
}
If you really need to use an array for the data structure based on your assignment, something you can try when adding and removing courses, is to construct a list from the array of courses, add or remove a course from that list, the convert the list back to an array of courses.
There's really 3 options here.
Option 1
If you're allowed to use List constructs:
private List<Course> courses = new ArrayList<Course>();
public void addCourse(Course aCourse)
{
if (aCourse == null)
{
return;
}
courses.add(aCourse);
}
Option 2
The uses arrays, but it doesn't scale. Assume that a teacher can only have a maximum of X courses, in my example 10:
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
return;
}
courses[numCourses] = aCourse;
numCourses++;
}
Option 3
This is identical to the previous item, but is a bit smarter in that it can resize the array... by creating a new one using the static method Arrays.copyOf
// Yes, I stole Duncan's variable names
private final int MAX_COURSES = 10;
private int numCourses = 0;
private Course[] courses = new Course[MAX_COURSES];
public void addCourse(Course aCourse) {
if (aCourse == null)
{
return;
}
if (numCourses >= courses.length)
{
int size = courses.length * 2;
courses = Arrays.copyOf(courses, size);
}
courses[numCourses] = aCourse;
numCourses++;
}
I'm a total newbie to Java, and until now all I've done was draw some shapes and flags. I'm struggling to understand the code I've been given. I need to access values stored in an ArrayList within another class. I'm not sure I'm making any sense, so here are the two classes Seat and Mandate:
package wtf2;
import java.util.*;
public class Seat {
public int index;
public String place;
public int electorate;
public String mp;
public String party;
public String prev;
public ArrayList<Mandate> results;
public Seat(int index, String place) {
this.place = place.trim();
this.index = index;
this.results = new ArrayList<Mandate>();
}
public void addMandate(Mandate m) {
//First candidate is always the MP
if (mp == null) {
mp = m.candidate;
party = m.party;
}
results.add(m);
}
public String toString() {
return "[" + this.index + "," + this.place + "]";
}
}
class Mandate {
public String candidate;
public String party;
public int vote;
public Mandate(String candidate, String party, int vote) {
this.candidate = candidate;
this.party = party;
this.vote = vote;
}
}
The main class contains code that feeds data from 2 text files into Seat and Mandate. From there I managed to access the date in Seat. Like here:
//Who is the MP for "Edinburgh South"
public static String qA(List<Seat> uk) {
for (Seat s : uk)
if (s.place.startsWith("Edinburgh South"))
return (s.mp);
return "Not found";
}
Now,instead of getting just the mp for Edinburgh South I need to get the vote values, compare them to each other, take the second biggest and display the associate party value.
Would appreciate any help, like how to access data from that Array would help me get started at least.
An element in an ArrayList is accesses by its index.
Seems you can just sort your ArrayList based on the vote values of the objects which are in the list.
For this you may want to look here: Sort ArrayList of custom Objects by property
Of course sorting is maybe too much for your given problem. Alternatively,
you may just iterate through the list and pick the two objects with the highest
votes values as you go.
I have Arraylist of objects ArrayList<Product> productDatabase. The object contains a String and a double and then these objects will be added to the productDatabase by addProductToDatabase(); as follows:
public void addProductToDatabase(String productName, double dimensions); {
Product newProduct = new Product(ProductName, dimensions);
productDatabase.add(newProduct);
}
I also want to make an Arraylist<ProductCount> productInventory which counts how many Product are accounted for. Before it can add to ArrayList<ProductCount> productInventory however, it should first check if the object details exist in the productDatabase while running addProductToInventory()
public Product getProduct(String name) {
for(i = 0; i < productDatabase.size(); i++)
if(productDatabase.get(i).contains(name) //Error: cannot find symbol- method contains.(java.lang.String)
return productDatabase.get(i)
}
public void addProductToInventory(String productName, double quantity)
{
Product p = getProduct(name);
productCount.add(new ProductCount(o, quantity));
}
Assume that you always have different objects (so nothing will have the same name), but you're always unsure of the dimensions (so when you input the same producttName + dimensions you edit the dimensions in it).
At the end of the day, you have to put all the items in it a large box and report what you've inventoried, so you also have a getProductQuantityTotal() and you have to getProductDimensionTotal()-- as the name suggests, get the total of number of objects you've counted, and the sum of the dimensions.
What do I have to add/change/remove about this code? Don't consider syntax first (because BlueJ checks for common syntax errors and I just typed this by hand). I'm sure that I'm missing a for statement somewhere, and I'm probably misusing contains() because it won't recognise it (I have import java.util.*; and import java.util.ArrayList;)
To answer the question in your post title: How to find a string in an object, for a list of those objects, here is some sample code that does this:
First, I created a trivial object that has a string field:
class ObjectWithStringField {
private final String s;
public ObjectWithStringField(String s) {
this.s = s;
}
public String getString() {
return s;
}
}
And then a code that populates a list of it, and then searches each for the string. There's no magic here, it just iterates through the list until a match is found.
import java.util.List;
import java.util.Arrays;
/**
<P>{#code java StringInObjectInList}</P>
**/
public class StringInObjectInList {
public static final void main(String[] ignored) {
ObjectWithStringField[] owStrArr = new ObjectWithStringField[] {
new ObjectWithStringField("abc"),
new ObjectWithStringField("def"),
new ObjectWithStringField("ghi")};
//Yes this is a List instead of an ArrayList, but you can easily
//change this to work with an ArrayList. I'll leave that to you :)
List<ObjectWithStringField> objWStrList = Arrays.asList(owStrArr);
System.out.println("abc? " + doesStringInObjExistInList("abc", objWStrList));
System.out.println("abcd? " + doesStringInObjExistInList("abcd", objWStrList));
}
private static final boolean doesStringInObjExistInList(String str_toFind, List<ObjectWithStringField> owStrList_toSearch) {
for(ObjectWithStringField owStr : owStrList_toSearch) {
if(owStr.getString().equals(str_toFind)) {
return true;
}
}
return false;
}
}
Output:
[C:\java_code\]java StringInObjectInList
abc? true
abcd? false
In the real world, instead of a List, I'd use a Map<String,ObjectWithStringField>, where the key is that field. Then it'd be as simple as themap.containsKey("abc");. But here it is implemented as you require. You'll still have quite a bit of work to do, to get this working as specifically required by your assignment, but it should get you off to a good start. Good luck!
I tried printStackTrace and I have coverted everything to static (I think)... however, lines 17 and line 38 are the problem... because of this error:
You picked up: Pickaxe
java.lang.NullPointerException
at item.addInv(item.java:38)
at item.main(item.java:17)
Description: Can be used to mine with.
Press any key to continue . . .
Line 17: anItem.addInv(1);
Line 38: arr.add("Dan");
And here is my code:
import java.io.*;
import java.util.*;
import javax.swing.*;
public class item
{
public static int attack, defense;
public static ArrayList<String> arr;
public static String name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat,earnedCoins,canEquip;
String stats[];
public static void main(String args[])
{
item anItem = new item();
ArrayList<String> arr = new ArrayList<String>();
anItem.addInv(1);
}
public static void addInv(int e) {
String iname = getItem(1)[0];
String idesc = getItem(1)[1];
int itypeOf = Integer.parseInt(getItem(1)[2]);
int iattackAdd = Integer.parseInt(getItem(1)[3]);
int idefenseAdd = Integer.parseInt(getItem(1)[4]);
boolean icanSell = Boolean.parseBoolean(getItem(1)[5]);
boolean icanEat = Boolean.parseBoolean(getItem(1)[6]);
int iearnedCoins = Integer.parseInt(getItem(1)[7]);
attack = attack + iattackAdd;
defense = defense + idefenseAdd;
System.out.println("You picked up: " + iname);
try {
arr.add("Dan");
} catch(NullPointerException ex) {
ex.printStackTrace();
}
System.out.println("Description: " + idesc);
}
public static String[] getItem(int e) {
String[] stats = new String[7];
String name = "Null";
String desc = "None";
String typeOf = "0";
String attackAdd = "0";
String defenseAdd = "0";
String canSell = "true";
String canEat = "false";
String earnedCoins = "0";
if (e == 1) {
name = "Pickaxe";
desc = "Can be used to mine with.";
typeOf = "2";
attackAdd = "2";
earnedCoins = "5";
}
return new String[] { name, desc, typeOf, attackAdd, defenseAdd, canSell, canEat, earnedCoins};
}
}
As you can see, it's those lines and I don't know what to do... :\
When you call the add() method on arr, it's not been initialized yet, hence, the NullPointerException.
Since you'll probably use the ArrayList in other methods as well, you should have that initialized in the constructor; ie:
public item() {
arr = new ArrayList<String>();
}
Variable arr is not initialized.
Variable arr in main() is not the same arr in function addInv()
Just initialize it in addInv to fix it.
String canEat = "false"; Why are you converting to and from strings?
You seem to have muddled an item class an inventory class.
Perhaps an Enum would be better:
public enum InventoryItem
{
PICKAXE("Pickaxe", "Can be used to mine with", ItemType.Tool,
5, 2, 0)
EPIC_PICKAXE("Super mega awesome Pickaxe", "Can be used to mine with, but epically", ItemType.Tool,
1000000, 100, 0)
public static enum ItemType {
TOOL,
WEAPON
}
public final String name, description;
public final ItemType type;
public final boolean canSell, canEat, canEquip;
public final int earnedCoins, attackAdd, defenseAdd;
private InventoryItem(String name, String description, ItemType type
int earnedCoins, int attackAdd, int defenseAdd,
boolean canSell, boolean canEat, boolean canEquip)
{
this.name = name;
this.description = description;
this.type = type
this.canSell = canSell;
this.canEat = canEat;
this.canEquip = canEquip;
this.earnedCoins = earnedCoins;
}
private InventoryItem(String name, String description, ItemType type
int earnedCoins, int attackAdd, int defenseAdd)
{
this(name, description, type,
earnedCoins, attackAdd, defenseAdd,
true, false, true);
}
}
Then you can just have List<InventoryItem> inventory = new ArrayList<InventoryItem>() within your player's class, and directly interface with that.
A few tips (one that does directly solve the problem):
1) wherever possible declare variables as private, or at most protected. I personally never use the "default" which is package level access (anything in the same package can see it).
2) Only use public for immutable values. An immutable value is something that cannot be changed (all members are final is the best way to ensure that, or no method modifies any values after the object is constructed and the variables are all private).
3) whenever possible always declare variables to be final (class variables, instance variables, parameters, local variables).
The one tip that directly helps you here is #3. Since you never assigned a value to "arr" it is null. If you declared it as final the compiler would force you do actually assign it a value, if you do not the code won't compile.
Doing that little thing will save you hours of time as you start programming. In my case I did something similar, not exactly the same (really I violated #2 sort of in a round about way) and it cost me about a week. I have been programming in Java for over 15 years now... if I can waste a week because of something like this think of how much time you can waste :-)