set methods in Java - java

Could anubody explain how to use set methods? Problem:
class Sonum {
private int prior;
public Sonum(int prior) {
this.prior = prior;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
class Tel {
// Please explain how can I set the value for prior? (for example 2)
}

Well, first you need an instance of Sonum on which you want to set the prior value. For example:
class Test {
public void foo() {
Sonum sonum = new Sonum(5);
// Use it with a prior of 5
// ...
sonum.setPrior(10);
// Now use it with a prior of 10
}
}

Sonum mySonum = new Sonum(1); //prior is currently 1
mySonum.setPrior(2); //now prior is 2

Take a deep breath. The Java Tutorial. Read it. You will understand.

Refer
Creating Objects & Using Objects
http://download.oracle.com/javase/tutorial/java/javaOO/objectcreation.html

"Setter methods" aren't magic. They're just regular methods. You need an instance of that class, and then you can call the methods on it. Just like any other Java object.

set method deal with a private value that we would like to prevent the direct way to him using our client, therefor there are get \ set method.
The biggest advantage of get \ set methods is the control ability !
We can for example control a minimum age when we want to set an age, and many other simple examples.
Example:
setAge (int age)
{
if ( age < 0 )
{
System.out.println ( "Wrong age !!" );
}
}
Now I think you can easily understand this HW :)

Related

How can I change code based on Method Argument?

public static void calculate(List<Person> data, String categoryType) {
for(int i = 0; i < categoryData.size(); i++) {
if(data.get(i).calculateCategoryOne() == firstPlace) {
...
}
}
}
If you see data.get(i).calculateCategoryOne(), the method call is for category one. The problem is that I need to copy-paste the entire code in a if-block for each category to just change this method call data.get(i).calculateCategoryTwo(), data.get(i).calculateCategoryThree(), ... data.get(i).calculateCategoryTen(),
While I can still make the logic work in this way, I feel it is redundant and not a good programming practice. Just to change one line of code, I would have to replicate the same code ten different times which will add nearly 500 lines of code.
So, my question is: Is there a way to dynamically change my method call based on the category type string argument.
I was thinking one possible way is to pass the method call in a string and convert it to a method call itself. For example, let's assume CategoryType string argument is "calculateCategoryOne()". So, data.get(i)."calculateCategoryOne()" would be recognized by the compiler as the method call itself. Is there a way to actually implement this?
I'm open to other ideas as well to reduce redundancy.
I would think using a functional interface would be appropriate here. You want different functionality depending on the categoryType, so passing in the function you want to use, rather than a String representation of it, would accomplish this.
#FunctionalInterface
public interface Calculate {
int calculate(Person data);
}
public static void calculate(List<Person> data, Calculate calculate) {
for(int i = 0; i < categoryData.size(); i++) {
if(calculate.calculate(data.get(i)) == firstPlace) {
...
}
}
}
and the call to the method would define what the calculation would be
calculate(list, p -> {
// calculation done here
});
or if this would happen frequently, you could predefine your categories once and pass those in:
Calculate categoryOne = p -> { ... };
Calculate categoryTwo = p -> { ... };
.
.
calculate(list, categoryOne);

Extract all True properties and add to a list

I have a java class with 3 boolean property like this
boolean isActive;
boolean isEnable;
boolean isNew;
every property is related to an enum (e.g. ACTIVE,ENABLE,NEW).
I want to have 2 lists of enum. One which has only the enums related to true property value and one for the false one.
just to be clear. using if-else statement I could have
Set<FlagEnum> flagSet = new HashSet<>();
Set<FlagEnum> falseFlagSet = new HashSet<>();
if (object.isActive()) {
flagSet.add(ACTIVE);
} else {
falseFlagSet.add(ACTIVE);
}
if (object.isEnable()) {
flagSet.add(ENABLE);
} else {
falseFlagSet.add(ENABLE);
}
if (object.isNew()) {
flagSet.add(NEW);
} else {
falseFlagSet.add(NEW);
}
is there a way to avoid all these if-else?
I tried with something like
Map<boolean, List<Pair<boolean, FlagEnum>>> res = Stream.of(
new Pair<>(object.isActive(), ACTIVE),
new Pair<>(object.isNew(), NEW),
new Pair<>(object.isEnable(), ENABLE))
.collect(Collectors.partitioningBy(Pair::getKey));
but the resulted structure is an additional complexity which I would like to avoid.
In my real case, I have more than 15 boolean properties...
You can simplify this in various ways. Which of them make sense, depends on your exact requirements.
You can derive the falseFlagSet trivially from the flagSet using EnumSet.complementOf after populating the flagSet:
EnumSet<FlagEnum> falseFlagSet = EnumSet.complementOf(flagSet);
This assumes that all FlagEnum values have corresponding flags. If that's not the case then you need to construct a EnumSet with all enums that have flags and subtract flagSet from that using removeAll.
#1 already removes the need for the else in your cascade, simplifying the code to
if (object.isActive()) {
flagSet.add(ACTIVE);
}
if (object.isEnable()) {
flagSet.add(ENABLE);
}
if (object.isNew()) {
flagSet.add(NEW);
}
If you have enough different flags, then you can create a mapping from getter method to FlagEnum value like this:
Map<Function<YourClass,Boolean>,FlagEnum> GETTERS = Map.of(
YourClass::isActive, FlagEnum.ACTIVE,
YourClass::isNew, FlagEnum.NEW,
YourClass::isEnable, FlagEnum.ENABLE);
Then you can use this to make the whole process data-driven:
EnumSet<FlagEnum> getFlagSet(YourClass yourObject) {
EnumSet<FlagEnum> result = EnumSet.noneOf(FlagEnum.class);
for (Map.Entry<Function<YourClass,Boolean>, FlagEnum> getter : GETTERS.entrySet()) {
if (getter.getKey().apply(yourObject)) {
result.add(getter.getValue());
}
}
return result;
}
If the number of flags is very big, then you could switch entirely to reflection and detect the flags and matching getters dynamically using string comparison, but I would not suggest that approach. If you need something like that then you probably should switch to a framework that supports that kind of feature and not implement it yourself.
That last two obviously only makes sense when the number of flags is big. If it's actually just 3 flags, then I wouldn't mind and just have 3 simple if statements.
As a slight tangent: GETTERS above should definitely be an immutable map (wrap it in Collections.unmodifiableMap or use something like Guava ImmutableMap) and it could be argued that the same applies to the return value of the getFlagSet method. I've left those out for succinctness.
You can use a private helper method for this.
private void addFlagSet(boolean condition, FlagEnum flagEnum,
Set<FlagEnum> flagSet, Set<FlagEnum> falseFlagSet) {
Set<FlagEnum> chosenFlagSet = condition ? flagSet: falseFlagSet;
chosenFlagSet.add(flagEnum);
}
Call it as:
addFlagSet(object.isActive(), FlagEnum.ACIVE, flagSet, falseFlagSet);
addFlagSet(object.isNew(), FlagEnum.NEW, flagSet, falseFlagSet);
addFlagSet(object.isEnable(), FlagEnum.ENABLE, flagSet, falseFlagSet);
You could probably use Reflection to get all methods, then check if a getReturnType() == boolean.class. Problem is the connection between the method's name and the enum. If every single one is named like the method without the 'is', you could use FlagEnum.valueOf() to retrieve the enum value from the method name and use it.
I think this could be the easiest and clearest way to do what I need
Map<Boolean, Set<FlagEnum>> flagMap = new HashMap<>();
flagMap.computeIfAbsent(object.isActive(), h -> new HashSet()).add(ACTIVE);
flagMap.computeIfAbsent(object.isEnabled(), h -> new HashSet()).add(ENABLE);
flagMap.computeIfAbsent(object.isNew(), h -> new HashSet()).add(NEW);
//to get TRUE set simply :
flagMap.get(true);
what do you think?

How to initiate a HashSet with Enumeration Values?

I am working with a library with a method with have a HashSet with enumaration parameter, and i ain't able to call that method. I think that question is probably easiest that i think, but i have this problem from two days.
Follow the method in library:
public int searchCard(HashSet<CardSlotTypeEnum> var1, int var2, OnCardInfoListener var3) {
if(var2 >= 0 && var3 != null) {
u.a().a(var1, var2, var3);
return 0;
} else {
return -2;
}
}
Follow the enumaration CardSlotTypeEnum:
public enum CardSlotTypeEnum {
ICC1,
ICC2,
ICC3,
PSAM1,
PSAM2,
PSAM3,
RF,
SWIPE,
}
Follow my code:
reader = deviceEngine.getCardReader();
OnCardInfoListener info = new OnCardInfoListener() {};
HashSet<CardSlotTypeEnum> teste = new HashSet<CardSlotTypeEnum>();
reader.searchCard(teste,60,info);
I'm having problems to initialize the 'teste' variable, this way was the only that don't are giving some message of error to me, but in this case the 'teste' aren't receiving nothing.
If someone could help me, I would be grateful.
It is a little strange that this library is using HashSet instead of EnumSet, but if that's what you're stuck with then so be it.
It's very easy to create an EnumSet that has all values in your enum class. You can then create a HashSet quite easily from that:
EnumSet<CardSlotTypeEnum> enums = EnumSet.allOf(CardSlotTypeEnum.class);
HashSet<CardSlotTypeEnum> teste = new HashSet<>(enums);
Edit
If you only want to add specific enum constants to the set, you can simply do that manually:
HashSet<CardSlotTypeEnum> teste = new HashSet<>();
teste.add(CardSlotTypeEnum.RF);
teste.add(CardSlotTypeEnum.SWIPE);

Setters with multiple parameters

I'm a little bit confused on what is the right way to use setters.
Is the preferable method to create a setters with only 1 parameter of the same object type like this one ?
public void setWebsite(String website) {
if(website ==null){
this.website = "";
}else {
this.website = website;
}
}
But i have 2 setters where i'm doubting about
public void setAddressClientList(List<AddressClient> addressClientList,Client client) {
//Here we add the customer to the address
if (!addressClientList.isEmpty()) {
for (AddressClient addressClient : client.getAddressClientList())
{
addressClient.setClient(this);
this.addressClientList.add(addressClient);
}
}
}
and
public void setProfessional(String companyName,String vatNumber ) {
this.professional = !(companyName == null || vatNumber == null);
}
this is the constructor
public Client(Client client,Company company,Client lastInsertClient) throws ClientException {
setCompany(company);
setActive(true);
setCustomField(client.customField);
setWebsite(client.website);
setVatNumber(client.vatNumber);
setPhoneNumber(client.phoneNumber);
setCurrency("notImplementedYet");
setFaxNumber(client.faxNumber);
setCompanyName(client.companyName);
setSalutation(client.salutation);
setLastName(client.lastName);
setEmail(client.email);
setFirstName(client.firstName);
setClientNumber(lastInsertClient);
setProfessional(client.companyName,client.vatNumber);
setAddressClientList(client.addressClientList,client);
}
Can someone explain if this what the best way to use the setters. And if the last 2 setters are not correct what would you suggest ?
Maybe you shouldn't use setters, maybe you should. Setters are mostly used to set a field of the Object that you want. Usually you set a single value at a time (or get it if that is the case), but there can be cases where values should be manipulated in pairs etc. This is a strictly semantic and almost philosophical question, but if you want to do it according to the best practices that people use, I suggest that you rename the method to something more descriptive to avoid confusion if somebody else works with your code. If this is a solo project, you might as well just comment it properly and be on your merry way.

Returning multplie values of the same type in Java

I need to return 3 values of an object I created in a method I created. I can put this code in my while loop and it executes how I want it to execute. But I want to keep it in a method just to modularize my program and keep the code organized. Im using the ACM library which is for academia purposes.
public GObject asteroidLocation(){
if(asteroid1.getX() >= AW)
{
asteroid1.setLocation(0,150);
}
else if(asteroid2.getX() >= AW)
{
asteroid2.setLocation(0,80);
}
else if(asteroid3.getX() >= AW)
{
asteroid3.setLocation(0,20);
}
return asteroid1, asteroid2, asteroid3;
}
What you need is a java.util.List
For your use-case you could just do this:
return Arrays.asList(asteroid1, asteroid2, asteroid3);
Your return type then would be List<GObject>
So return a List<Asteroid> or whatever type asteroid is. Even better is have an object you create that has a List<Asteroid>, has a getAsteroids() method and return that.
Have you tried Tuples (https://en.m.wikipedia.org/wiki/Tuple) and Triples?
Java don't provide any but it's pretty straightforward to implement. I can give you an example if needed.
Instead of returning the value outside the if condition return it from within. For example,
if(asteroid1.getX >= AW)
{
asteroid1.setLocation(0,150);
return asteroid1;
}
This way you could simplify the code and pass only one return value to the class
A direct answer to you question "multplie values of the same type in Java" would be:
An array: GObject[]
Any generic collection, e.g. List<GObject>

Categories

Resources