Difference boolean[] b = {false} vs. boolean b = false? [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 4 years ago.
Improve this question
What is the difference between:
boolean[] cameraPermissionGranted = {false};
and
boolean cameraPermissionGranted = false;
??
There is nor problem, both work.
I just want to know what is the difference on the memory for instance.
What is the difference regarding prerformance issues..

boolean[] cameraPermissionGranted = {false}; create a boolean array, it's first element is false.
boolean cameraPermissionGranted = false; create a boolean variable, it's value is false.

Difference between these primarily is that
boolean[] cameraPermissionGranted = {false};
is an array that persists boolean type of data initialized with single element false at present unless resized(re-initialized) while
boolean cameraPermissionGranted = false;
is just an attribute that is initialized as false and can be updated thereafter.
One of the very intuitive example that comes to my mind for that is usage in lambda's :
boolean[] cameraPermissionGranted = {false};
boolean cameraPermission = false;
List<Integer> list = new ArrayList<>();
list.forEach(a -> {
cameraPermissionGranted[0] = true; // effectively final
// cannot use cameraPermission
});

The first one creates a single element boolean array, the other creates a boolean type.
The former is often used in places where final is required and element modification is desirable, such as closures, although modern Java versions introduce other more readable and less subversive techniques. It is also somewhat analogous to the reference type of C++: you can pass the array reference to a function and that function can modify the array element and such modifications will be seen by the caller.

One reason of the use of the first one would be to mimic a C++ pass-by-reference. Consider the following example in C++:
void toggleValue(bool &b){
b = !b;
}
It seems hard to do it in Java since you cannot pass a parameter by reference. But with a singleton array, you can mimic the same behavior :
private void toggleValue(boolean[] b){
b[0] = !b[0];
}

Related

Referencing a local variable while iterate a HashMap -> local variables referenced from a lambda expression must be final or effectively final error

today i wanted to work on some projects i wanted to finish where i get an exception that i can not reference to a local variable from a lambda expression.
I have a method where i give two values and th method checks if the value-pair is already in the HashMap
public void METHOD_NAME(Value value1, Value value2) {
boolean founded = false;
//values is the name of the HashMap
this.values.forEach((value1Map, value2Map) -> {
if(value1Map == value1&&value2Map == value2){
this.doSomeStuff();
founded = true;
}
});
}
and when its finished i want to read out the boolean needing to know if he doesent found it
founded = false;
how can i set founded in this lambda or are there any other ways to do this ?
You can use the atomic variants of primitives in lambdas. Replace
boolean founded = true
by this
final AtomicBoolean found = new AtomicBoolean(false);
and set it in within your lambda like this
found.set(true);
By the way, it is absolutely ok NOT to replace every iteration by a lambda. The for-loop still works and has its advantages over lambdas in some cases.
I've changed founded to found as Tom indicated in the comments of your question. Moreover, you should verify if you want to make the comparison with == instead of equals

How do you know you need to define a new method? [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 5 years ago.
Improve this question
We want each method to do a distinct task, right? How do you draw that line?
For example, say I have a class with an int array that I need to have set to certain numbers when the class is constructed. Should I loop through the array right there or make a separate method for what is ultimately a simple task?
Make a new method whenever you have a sensible name for one. When you have a good name for a new method, it suggests that what you're doing there is a separate task and potentially reusable.
Note that this is just a rule of thumb and may not apply to all cases. Another rule is to make a new method if your current method is too long (I've heard 48 lines cited as an upper bound).
Here is a sample class that I hope points out what you are looking for:
class Sample {
private int[] myInts = null;
// we need a constructor if we are going to pass in stuff
// if we don't provide a constructor, java will create one for us
public Sample(int[] inputs) {
// I can just set this array, I don't need a separate method to
// loop through and create a new array and copy the old one.
myInts = inputs;
}
// here we are going to do something discreet, so I need a new method.
public int add() {
int returnValue = 0;
for (int i = 0; i < myInts.length; i++) {
returnValue += myInts[i];
}
return returnValue;
} // end my "add()" method
} // end my Sample class

How do i convert a Set into 2D array in java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So, i have a Set, where each instance has four fields.
I want to convert it to Array[i][j], where each [j] row would represent an instance.
Edit:
Ok. Sorry for my bad question construction. Im trying to make a programm, which would represent a TreeSet data in table with javax.swing.table.AbstractTableModel.
Actual problem was in AbstractTableModel's getValueAt(int r, int c) method, which needs an index for every table element. Since sets don't have an index, i decided to convert data into 2D array just for table because it makes things simple. But now i'm stuck with setValueAt(Object value,int r,int c), where i should convert edited data back to Set.
Now i'm thinking of converting this Set to List instead of array since it would be easy to transfer back.
Let be a:
public class MyClassWhithFourFields {
String field1;
int field2;
Object field3;
double field4;
}
Now you can declare a set with this template:
Set<MyClassWhithFourFields> mySet = new HashSet<MyClassWhithFourFields>();
In your Set are your objects, which has 4 fields.
If you want to declare a 2 dimension array, than what type should be?
- the most common parent can be, and in this case it is the Object.
So declare a function an implement it:
Object[][] transformSetTo2dArray(Set < MyClassWhithFourFields > mySet) {
if (mySet == null) {
return null;
}
Object[][] result = new Object[4][mySet.size()];
int j = 0;
// iterate the set:
for (MyClassWhithFourFields myObject: mySet) {
myObject[0][j] = myObject.field1;
myObject[1][j] = myObject.field2;
myObject[2][j] = myObject.field3;
myObject[3][j] = myObject.field4;
j++;
}
return result;
}

Remove all pointers to an object 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 7 years ago.
Improve this question
OK, here is the thing. I have multiple pointers to an object and I want to remove both of them. I have simplified it, below, so don't bother asking why on earth I would try the thing below :)
String first = "ASSIGNED";
String second = test;
second = null;
System.out.println(first);
In the example above, the output still results in "ASSIGNED". However, I want first to be no longer assigned. In the example above, it is easy, by setting it to null, but in my real example, this is not possible (first being passed into a method, where I want to remove the assingment).
EDIT:
So, I guess the question is, if it is possible to remove all pointers to a given object.
Apparently it was a bit vague what I was asking, so let's try to give a better example:
String first = "Assigned";
doSomethingAndRemove(first);
public void Remove(String string) {
//Do something
//...and remove
string = null;
}
The thing is that first still is referencing to "Assigned"... But from what I read in the answers so far, there is no way around this?
No, it is not possible to remove all "pointers" to a given object, for one because Java doesn't have pointers, they are called references.
Neither Java nor the JVM knows all references to a given object. This is why the garbage collector has to scan everything to find unused objects.
You have to clear references, and you cannot clear a reference variable that was used to pass a parameter from within the called method, because Java is pass-by-value, meaning the reference (not the object) is copied.
Example:
public static void main(String[] args) {
String var1 = "Hello";
doSomething(var1); // The value of var1 is copied to param1
}
private static void doSomething(String param1) {
param1 = null; // Only clears the param1 reference
var1 = null; // Cannot do this, because doSomething() does not have access to var1
}
Only code in method main can change the reference value of var1.
Update
If you want method doSomething to be able to update var1 to a different value, incl. null, then a common practice is to simply return the updated value.
public static void main(String[] args) {
String var1 = "Hello";
var1 = doSomething(var1);
}
private static void doSomething(String param1) {
// do something with param1
return "Goodbye";
}
This of course only works if you didn't already have a different kind of return value, and only works for a single value.
Output (and In/Out) parameters can be simulated in Java using the holder pattern, e.g. see Output Parameters in Java
C# can do it using ref, but Java cannot. The following is the last resort in Java if you must do it.
public class Nullify
{
public static void main(String[] args) {
String[] first = { "ASSIGNED" };
System.out.println("first[0] = " + first[0]);
nullify(first);
System.out.println("first[0] = " + first[0]);
}
private static void nullify(String[] array) {
array[0] = null;
}
}
String s=ASSIGNED;
String s2=s;
String s2=null; // means just remove the link s2 is pointing to
System.out.println(s); // print ASSIGNED
seen the picture.
if you want to remove you have to assign null to all individual objects.

Java - If I change an item in a list, will the Object in the list be changed too?

I know this has probably been asked before but I can't find a specific answer to my specific question. I have already tried to grasp Java's handling of references but this still puzzles me. Consider the following:
public class Question
{
private boolean isCorrect;
public void setCorrect (boolean _isCorrect) {
isCorrect = _isCorrect;
}
}
Now, in another file, somewhere in the code:
/**
* questionList is List<Question> questionList = new ArrayList<Question>();
* With various Question's added already with various isCorrect values.
*/
for (int i = 0; i < questionList.size(); i++) {
Question q = (Question) questionList.get(i);
q.setCorrect(true);
}
Will this set each Question's isCorrect in the questionList to true? As I understand Java (and I don't think I do) it should. But does it?
Thank you
Yes, it will. It's the same object referenced in two places.
Yes. You should learn about pointers and references from the Java Tutorial. The List contains pointers to the slots in memory where the Question is stored. So take actions on the pointer, you are taking actions on the sot in memory itself
Yes, it does. Understand this
Question q = (Question) questionList.get(i);
q is simply a reference of type Question that refers to the underlying object returned by get. No copy of the object is implicitly created.
Yes, because the variable q is pointing to the object in the list in memory. Therefore, any methods you call on q are getting called on the object in memory.
It should be changed to true, but for speed's sake, why not:
for(int loop = 0; i < questionList.size(); loop++){
questionList.get(loop).setCorrect(true);
}

Categories

Resources