How to add multiple values to an Object ArrayList? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The problem should be on the createClass() method... is it wrong to use classes.add(this)?
private static ArrayList<VirtualClass> classes = new ArrayList<VirtualClass>();
private boolean isPrivate;
private String className;
private String methodName;
public void setVirtualClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
}
public void createClass(String name, String method, boolean isP){
this.className = name;
this.isPrivate = isP;
this.methodName = method;
classes.add(this);
}
More details on the problem: Failed to store values in ArrayList of class object. (CODE EDITED)

I suppose you want to keep a record of all created classes?
It is generally bad practice to pass out this in a constructor because, by definition, this hasn't been constructed yet. In this instance I don't think it will cause problems but it certainly doesn't smell right.
I would consider using a static factory method or another form of factory pattern so that you can split up object creation and the storing of instances.

No one can tell you whether it is right or wrong unless you tell what you are trying to do.
If what you are doing is something like : (assume your class is called Foo)
Foo foo = new Foo();
foo.createClass("Blablabla", "method1", true);
foo.createClass("AnotherClass", "method2", true);
something like that, then yes, you are probably wrong. Because what you are doing is simply changing the only Foo instance with different attribute, and adding the same object to the list.

Related

Java class has only one constructor, no parameter for constructor, all instances of that class will point to the same object in the heap? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
Have the following case:
class Bond {
private static int price = 5;
public boolean sell() {
if(price<10) {
price++;
return true;
} else if(price>=10) {
return false;
}
return false;
}
public static void main(String[] cash) {
new Bond().sell();
new Bond().sell();
new Bond().sell();
System.out.print(price);
Bond bond1=new Bond();
System.out.print(price);
}
}
It will print: 8 9.
Will all instances that will be made, will point to the same object in the heap?
There's a very simple rule in Java: new SomethingOrOther() will always create a new object (unless it somehow produces an exception).
So the answer is obviously: no, the main method you posted will create 4 instances of Bond.
Those instances happen to not have any fields that makes them different in any interesting way, but they are distinct instances.
The reason it "looks like" only one instance exists is that your price field is static, which means it belongs to the class Bond itself and not to an individual instance, which also means there's only one price ever, no matter how many instances you have (yes, even if there are no instances at all).
Remove static keyword of "price" to answer it yourself.
static variables hold the same value across all the object instances.

Setting the Value to an Object by using Void or return type approach [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I have Employee class and I am trying to set a value to employee name property:
public class Employee {
private String name;
private String id;
// setters and getters
}
I have got two options: by using void or using a return type.
public class EmpClient {
public static void main(String[] args) {
Employee emp = new Employee();
EmpClient emp_client = new EmpClient();
emp_client.setNameToEmployee(emp);
System.out.println(emp.getName());
}
public void setNameUsingVoid(Employee emp) {
emp.setName("Mark");
}
public Employee setNameToEmployee(Employee emp) {
emp.setName("Taylor");
return emp;
}
}
This is my code and through both the approaches, it works.
Please let me know what is the preferred and more efficient way? What are the pros and cons of using each of the methods, and under what circumstances should they be used?
It depends on what you want the method to do. For most cases setNameUsingVoid() method would be suitable. You want to assign a name to the employee and this method achieves that.
When instead you have this statement in your main method.
setNameToEmployee(emp);
The desired assignment is done and additionally, a reference is also returned. Here you are not using the returned value, so it is just unnecessary extra work. So if you are going to use the statement in the above fashion, use setNameUsingVoid() instead.
Note: According to the Java Language Specification, the above statement is a valid statement though the returned value is not being used. For more info on the validity of such statements
If instead you were to use setNameToEmployee() in this way:
Employee e1 = setNameToEmployee(emp);
You should opt for using this function over the other one. However in this specific use case the statement makes no sense at all because you are idly making a second copy of your Employee object. Summing up:
In this case (or any case where you pass a reference at return the same thing), it is best to use setNameUsingVoid(), as it is very difficult to think of a case where setNameToEmployee() might actually be beneficial.

Is there a way of making optional atributes in java? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I need to code this class in java. I thought of making a bunch of constructors but i dont think thats the best way to do it. Id like to know if java has some sort of optional parameters or attributes to make this simpler.
You can do it with one constructor with varargs, since all fields of your class are of type String:
public class Address {
private String street;
private String city;
private String postalCode;
private String state;
private String country;
public Address(String... params) {
street = params[0];
city = params[1];
//etc. Just take care to pass the arguments in the order you are
//assigning them when you call the constructor. Also check the size
//of varargs first so you don't assign arguments that don't exist.
}
}
And then call it like so to set only the street and city:
Address adress = new Address("myStreet", "myCity");
An alternative is to have one constructor with all the arguments, and if you don't want to set a value, pass null to the constructor in place of the corresponding parameter:
Address adress = new Address("myStreet", "myCity", null, null, null);

Wrapping an Integer [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to make a constructor that accepts an integer to be wrapped. I currently have:
public class IntegerRateable implements Rateable {
private Integer object;
public IntegerRateable(Integer object) {
this.object = new Integer(object);
}
I am unsure what is wrong with my code. I was under the impression that this should allow it to be wrapped.
If what you want is, your IntegerRateable class to contain an Integer as member variable, try this:
public class IntegerRateable implements Rateable {
private Integer object;
public IntegerRateable (int number) {
this.object = number;
}
Then, just instantiate IntegerRateable object as:
IntegerRateable integerRateable = new IntegerRateable(5);
You may first want to check your braces, you're missing a closing brace }.
If that's not the problem, I'am assuming that the problem is in this line
this.object = new Integer(object); . There is nothing wrong with this, it's just that it using the Integer constructor has been deprecated which you can find out more about here https://docs.oracle.com/javase/9/docs/api/java/lang/Integer.html#Integer-int-
So the preferred way of doing it would be to do this.object = new Integer.valueOf(object);
EDIT: Although, I don't see a point in doing this since you can just do this.object = object;

Value of Optional.of("xxxx") in Java Programming [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Please consider the following java code:
Optional.of("some.constant.value")
How is using Optional.of() of any value when the parameter is a constant?
Optional is generally used as return value of a function that may or may not return a value. It's a technique to avoid dealing with null-values.
E.g. assuming you have a function that returns an Optional<Integer>, you can use it to provide a default value:
int x = person.getAge().orElse(42);
The factory function you are refering to is how an Optional is constructed in the called function:
public Optional<Integer> getAge(){
if(this.age == null)
return Optional.empty();
return Optional.of(this.age);
}
This is entirely contextual, and without that context it's impossible for anyone to really say.
But... As a couple of times I've seen things like this be useful (maybe you can identify which one is relevant to your given circumstance:
An interface where some method is an Optional.
interface PotentiallyLimited {
OptionalInt getLimit();
}
class LimitedToTen implements PotentiallyLimited {
private static final OptionalInt LIMIT = OptionalInt.of(10);
#Override
public final OptionalInt getLimit() {
return LIMIT;
}
}
In this case, having the variable stored as a constant stops it having to generate a new instance every time.
A class where some dependency would return an Optional, but may not be present.
class Thing {
private static final Optional<String> DEFAULT_PREFERENCE = Optional.of("blue");
private final #Nullable PreferenceProvider provider;
public void useDependency() {
final Optional<String> preference;
if (dependency != null) {
preference = provider.getPreference();
} else {
preference = DEFAULT;
}
// Use the preference here...
}
}
Again, having it as a constant means you don't need to create a new instance on every invocation.
One final case I've seen, say you have some interface which has a sort of boolean isError(); and an additional Optional<String> getErrorReason();. It's perfectly reasonably to have an implementation which always represents an error, then explicitly setting the Optional from a known constant String again helps avoiding creating lots of instances.
I'm sure there's plenty of other times it might be useful to do this.

Categories