How to invoke contains directly on class rather than collection - java

I would like to know how to be able to invoke the contains method directly on my class instead on its ArrayList variable. Best way to explain is really with the code below.
Thanks for your help.
public class Chord {
ArrayList<Note> notes;
// some more stuff not here
}
cmaj = new Chord("Cmaj");
cnote = new Note("C");
// what I have
cmaj.getNotes().contains(cnote);
// what I would like, is this possible, how?
cmaj.contains(cnote);

Well you can just write the method yourself:
public class Chord {
private final List<Note> notes;
...
public boolean contains(Note note) {
return notes.contains(note);
}
}

This is typical example of proxy methods (see proxy patter).
public class Chord {
private final List<Note> notes = new ArrayList();
public boolean contains(Note note) {
return notes.contains(note);
}
}
When you are using this type of methods, you should double check that reference is set before the object is delivered to client. If you do not pay attention you will get NullPointerException. And Try to stay consistent, if you decide to use contains in that way, add, remove and reset should also be implemented. And then the getter is no more required.

Write a method contains() inside chord that simply delegates the call the the arraylist as below:
public class Chord {
ArrayList<Note> notes;
public boolean contains(Object o) {
return notes.contains(o);
}
}

Add a method contains encapsulating the arrayList´s contains:
public class Chord {
ArrayList<Note> notes;
// some more stuff not here
public boolean contains(Note note){
return notes.contains(note);
}
}

Related

Using the Step Builder pattern for the creation of a complex object that contains an instance variable that is a list

Let's say I want to construct an instance of the following object:
private class ComplexObject {
private int param1; // Required Parameter
private int param2; // Required Parameter
private int param3; // Required Parameter
private List<Integer> listParam4; // This list should contain atleast one Integer
private ComplexObject() {
this.listParam4 = new ArrayList<Integer>();
}
}
I'm trying to use the Step Builder pattern to construct this object, so that a user sets the value of the parameters in order. The main problem that I'm facing is with creating an interface for the last step. I want to expose the build() method after the user has provided atleast one integer that I can add in listParam4. At the same time I also want to give the user the option of providing more integers to add to the list before calling the build() method. I would really appreciate if someone can provide me a way of doing this or suggest an alternative approach in case I'm approaching this problem incorrectly.
Here is the code that I currently have to achieve this:
public interface SetParam1Step {
SetParam2Step setParam1(int param1);
}
public interface SetParam2Step {
SetParam3Step setParam2(int param2);
}
public interface SetParam3Step {
AddToParam4ListStep setParam3(int param3);
}
public interface AddToParam4ListStep {
// Not sure how to create this interface
}
public static class ComplexObjectBuilder implements SetParam1Step, SetParam2Step, SetParam3Step, AddToParam4ListStep {
private int param1;
private int param2;
private int param3;
private List<Integer> listParam4;
private ComplexObjectBuilder() {
// Prevent Instantiation
}
#Override
public AddToParam4ListStep setParam3(int param3) {
this.param3 = param3;
return this;
}
#Override
public SetParam3Step setParam2(int param2) {
this.param2 = param2;
return this;
}
#Override
public SetParam2Step setParam1(int param1) {
this.param1 = param1;
return this;
}
// Needs to implement the build() method and the methods that would eventually be added to the AddToParam4ListStep interface.
public static SetParam1Step newInstance() {
return new ComplexObjectBuilder();
}
}
AddToParam4ListStep should simply have an add() method returning yet another interface (AddToParam4ListOrBuild) that would allow to add() more parameters (returning itself) and to build the final object:
public interface AddToParam4ListStep {
AddToParam4ListOrBuild add(Integer toAdd);
}
public interface AddToParam4ListOrBuild {
AddToParam4ListOrBuild add(Integer toAdd);
ComplexObject build();
}

Generic array with Polymorphism

I have created a base interface which is implemented by some objects and I also have an array of interfaces which given a string return the objects mentioned. (a bit difficult to explain, better look the code :D) Then I want to pass this to the global object through some overloaded methods (at the beginning looked super clever, but it now seems technically impossible) Could I get any closer to what I want?
interface Stats { }
public class ObjectA implements Subscriber.Stats { // MORE THINGS }
public class ObjectB implements Subscriber.Stats { // MORE THINGS }
// MORE OBJECTS
This is the second interface which transforms a String into one of the classes from above
public interface Parser<T extends Stats> {
T parse(String data);
}
Now I have an array of implementations of the this interface I want to give me different results (ObjectA, ObjectB, ObjectC ..)
private final Parser<Stats>[] parsers = new Parser[] {
new Parser() {
#Override
public Stats parse(String data) {
return new ObjectA();
}
},
new Parser() {
#Override
public Stats parse(String data) {
return new ObjectB();
}
}
};
Now comes the "clever" part where I want to make something that may not be possible.
If I loop the array of parsers and each position gives me ObjectA, ObjectB due to Polymorphism I could call an overloaded method of a class with a signature like push(ObjectA) push(ObjectB), right??... Well this obviously doesn't work but is there any strategies I could use to accomplish this?
The loop would be:
for (int i = 0; i < operations.length; i++) {
dataHolder.push(parsers[i].parse(operations[i].getResult()));
}
EDITED
The problem is the method T parse (String value) is treated as if it returns Stats and not T extends Stats therefore when I call push it says there is no push(Stats) method
If I got it correctly, your dataHolder interface looks like this:
public interface DataHolder {
void push(ObjectA a);
void push(ObjectB b);
}
In that case really your loop cannot benefit from the overloaded methods, because at cimpile time, it only knows about parsers of Stats.
To achieve your goal you need to use the visitor pattern, and update your Stats hierarchy like this:
public interface Stats {
void accept(DataHolder holder);
}
public class ObjectA implements Stats {
void accept(DataHolder holder) {
holder.push(this); // this is ObjectA, so push(ObjectA) is used
}
}
public class ObjectB implements Stats {
void accept(DataHolder holder) {
holder.push(this); // this is ObjectB, so push(ObjectB) is used
}
}
Now if you do:
new Parser<Stat>().parse(input).accept(dataHandler);
It will use the propper overloaded push method (I didn't rewrite your loop, because I'm not sure if I unerstadt it properly, bu hopefully you can apply it yourself).
Sounds reasonable to me. Just try it.
String dataToParse = "wklhbglbwbgiwegbuwegbwe";
for(Parser p : parsers){
//The definition of each parser will be called and everything works.
System.out.println(p.parse(dataToParse));
}
Also you can just:
public void push(Object obj){
System.out.println(obj.getClass().getCardionalName());
//Or anything else you want to do with it.
}

Make several classes have the same attributes without inheritance

I'm facing a problem in Java.
I need to have several classes with the same attributes ( for example a Position and a boolean isWalkable ).
But I don't want these classes to inherit from a class Element because that would prevent me from using inheritance later.
I thought of an interface (so that the interface has the attributes), but apparently you can't have an interface inherit from a class.
There must be a way because otherwise I would have to copy/paste my attributes and there methods.
Thanks in advance for anyone who has an idea on how to overcome this problem.
For this, I would consider composition over inheritance.
public class Main {
public static void main(String[] args) {
AgentWrapper agentWrapper = new AgentWrapper(new Agent1(), false, 1);
System.out.println("isWalkable: " + agentWrapper.isWalkable());
System.out.println("position: " + agentWrapper.getPosition());
agentWrapper.getAgent().doSomething();
}
}
interface Agent {
void doSomething();
}
class Agent1 implements Agent {
public void doSomething() {
System.out.println("Agent1");
}
}
class Agent2 implements Agent {
public void doSomething() {
System.out.println("Agent1");
}
}
class AgentWrapper {
private final Agent agent; //Wrapped instance.
private final boolean isWalkable;
private final int position;
public AgentWrapper(Agent agent, boolean isWalkable, int position) {
this.agent = agent;
this.isWalkable = isWalkable;
this.position = position;
}
public Agent getAgent() {
return agent;
}
public boolean isWalkable() {
return isWalkable;
}
I suspect you might need an interface anyway, if you want to treat your objects generically - e.g. loop over all of them and draw each one. E.g. assuming your elements include "cats" and "houses":
interface Element{
public point getPosition();
public boolean isWalkable();
}
class Cat implements Element{
private Point position;
private String catBreed; // example of cat-specific data
public point getPosition() {return position;}
public boolean isWalkable() {return true;} // cats can walk
...
}
class House implements Element{
private Point position;
private String streetAddress; // example of house-specific data
public point getPosition() {return position;}
public boolean isWalkable() {return false;} // houses cannot walk
..
}
// Finally, using that common interface:
Element[] allGameObjects= {new Cat(...), new Cat(...), new House(...) };
for(Element e:allGameObjects)
draw(e, e.getPosition());
That was good enough for several system I wrote... but as other replies correctly mentioned, you might refactor to use composition - however it might not be a 100% clear-cut. I mean, I can understand if you feel Cat or House should be managed independently from their position... but what about isWalkable?
// Position is easy to separate:
class Cat { String catBreed; ... }
class House{ String streetAddress; ... }
class ElementWrapper implements Element{
Point position;
Object theObject; // could hold Cat or House
public Point getPosition() {return position;}
// however, isWalkable is a bit tricky... see remark below
}
But 'isWalkable' is tricky because in classic polymorphism you'd expect House/Cat to tell you whether they can walk (meaning they should implement an interface anyway). If you absolutely don't want (or cant) have it, you may compromise on polymorphism and do something in the lines of instanceof (if theObject is instanceof Cat then it can walk, if it's instanceof House it cannot walk, etc).
You can extend an abstract base class(containing nothing) or You can use the Decorator pattern as somebody suggested in the comments, for more information related to Decorator pattern you can read this link.

Java function on function [duplicate]

I want to achieve method chaining in Java.
How can I achieve it?
Also let me know when to use it.
public class Dialog {
public Dialog() {
}
public void setTitle(String title) {
//Logic to set title in dialog
}
public void setMessage(String message) {
//Logic to set message
}
public void setPositiveButton() {
//Logic to send button
}
}
I want to create method chaining that I can use as follows:
new Dialog().setTitle("Title1").setMessage("sample message").setPositiveButton();
or like
new Dialog().setTitle("Title1").setMessage("sample message");
or like
new Dialog().setTitle("Title1").setPositiveButton();
Have your methods return this like:
public Dialog setMessage(String message)
{
//logic to set message
return this;
}
This way, after each call to one of the methods, you'll get the same object returned so that you can call another method on.
This technique is useful when you want to call a series of methods on an object: it reduces the amount of code required to achieve that and allows you to have a single returned value after the chain of methods.
An example of reducing the amount of code required to show a dialog would be:
// Your Dialog has a method show()
// You could show a dialog like this:
new Dialog().setMessage("some message").setTitle("some title")).show();
An example of using the single returned value would be:
// In another class, you have a method showDialog(Dialog)
// Thus you can do:
showDialog(new Dialog().setMessage("some message").setTitle("some title"));
An example of using the Builder pattern that Dennis mentioned in the comment on your question:
new DialogBuilder().setMessage("some message").setTitle("some title").build().show();
The builder pattern allows you to set all parameters for a new instance of a class before the object is being built (consider classes that have final fields or objects for which setting a value after it's been built is more costly than setting it when it's constructed).
In the example above: setMessage(String), setTitle(String) belong to the DialogBuilder class and return the same instance of DialogBuilder that they're called upon; the build() method belongs to the DialogBuilder class, but returns a Dialog object the show() method belongs to the Dialog class.
Extra
This might not be related to your question, but it might help you and others that come across this question.
This works well for most use cases: all use cases that don't involve inheritance and some particular cases involving inheritance when the derived class doesn't add new methods that you want to chain together and you're not interested in using (without casting) the result of the chain of methods as an object of the derived.
If you want to have method chaining for objects of derived classes that don't have a method in their base class or you want the chain of methods to return the object as a reference of the derived class, you can have a look at the answers for this question.
Just add a static builder method, and create another set of the setter methods.
For example
class Model {
private Object FieldA;
private Object FieldB;
public static Model create() {
return new Model();
}
public Model withFieldA(Object value) {
setFieldA(value);
return this;
}
public Model withFieldB(Object value) {
setFieldB(value);
return this;
}
}
...
And use it like
Model m = Model.create().withFieldA("AAAA").withFieldB(1234);
example of reducing the amount of code required to show a dialog would be:
package com.rsa.arraytesting;
public class ExampleJavaArray {
String age;
String name;
public ExampleJavaArray getAge() {
this.age = "25";
return this;
}
public ExampleJavaArray setName(String name) {
this.name = name;
return this;
}
public void displayValue() {
System.out.println("Name:" + name + "\n\n" + "Age:" + age);
}
}
another class
package com.rsa.arraytesting;
public class MethodChaining {
public static void main(String[] args) {
ExampleJavaArray mExampleJavaArray = new ExampleJavaArray();
mExampleJavaArray.setName("chandru").getAge().displayValue();
}
}
In case if you are using lombok, you can use parameter in your lombok.config:
lombok.accessors.chain = true
Or for particular data classes you can declare #Accessors(chain = true) annotation:
import lombok.experimental.Accessors;
#Accessors(chain = true)
#Data
public class DataType {
private int value;
// will generate setter:
public DataType setValue(int value) {
this.value = value;
return this;
}
}

How to write Class in Android Java that give me return more then one object ? (like in C# I can do same with struct)

I want to reurn my custom object in Java. How I can do. From looking to people's answer it's look like Java don't support custom object.
https://stackoverflow.com/a/11701816/713789
public class FinanceManager {
public String Compname;
public FinanceManager(String Compname){
this.Compname = Compname;
}
public static CustomValueReturn(){
return ;;
// I need to return a custom object which return too many object as single object.
}
}
Someone please help me how I can do it in java. I have tried .net very few and in .net I make struct and return a struct who have a lot of detail so function can return bunch of detail instead of Single string or object.
try:
public static class MyCompound {
public final String a;
public final String b;
public MyCompund(String a,String b) {
this.a=a;
this.b=b;
}
}
public MyCompound testCompundReturn(String input) {
return new MyCompound(input,"hello");
}
It's quite simple. Create a model class for your return. For instance, say you want to return CustomObject.
class CustomObject {
private blabla ..;
/getters setters and what not
}
Now in your "returning method"
public class FinanceManager {
private CustomObject instanceOfCustomObject;
public String Compname;
public FinanceManager(String Compname){
this.Compname = Compname;
this.instanceOfCustomObject = new CustomObject();
}
public CustomObject getInstanceOfCustomObject(){
return this.instanceOfCustomObject
// I need to return a custom object which return too many object as single object.
}
}
Use a container, Map, List or an array.
If you want to return a custom object just create a class for your custom object and return an instance of that class:
class mycustomobject {
int int1;
String string1;
//and so on...
}
For more information see this tutorial
If you want to return multiple objects use a container or an array.

Categories