This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 7 years ago.
Following Question. I have a big amount of ArrayList attributes (basically the same as Kreuzlagerort20kg etc). Instead of initializing them all in the constructor (the part commented out) i'd love to initialize them inside the fillLager() method, making it possible to call the method inside the constructor and have them initialized and filled then. If i do it in the code, i always get a nullpointerexception.
Is it possible and/or sensible to initialize an arraylist inside a method, without getting said nullpointer?
import java.util.ArrayList;
public class Lager {
private ArrayList<Screws> KreuzLagerort20kg,KreuzLagerort50kg;
public Lager(){
//KreuzLagerort20kg = new ArrayList<Screws>();
//KreuzLagerort50kg = new ArrayList<Screws>();
fillLager(1,KreuzLagerort20kg,20);
fillLager(1,KreuzLagerort50kg,50);
}
public void fillLager(int typ,ArrayList<Screws> lager,double lagerGewicht){
lager = new ArrayList<Screws>();
// code that loops through combinations and adds them to the arraylist
}}}}}}
You can't call new on a variable passed into a method and still have the calling method refer to the original variable, as Java passes by reference. When you call new X() then there is a new reference and the method which called your other method will not know the variable is now pointing at another reference...
e.g.
public void methodA() {
String s = new String("AAAAA");
methodB(s);
System.out.println(s);
}
public void methodB(String referredString) {
referredString = new String("BBBBB");
}
calling methodA will print "AAAAA"
You will need to initialise in the constructor, or make the method return the variables you passed in...
public void methodA() {
String s = new String("AAAAA");
s = methodB(s);
System.out.println(s);
}
public String methodB(String referredString) {
referredString = new String("BBBBB");
return referredString ;
}
calling methodA will now print "BBBBB"
Alternatively - make the string declared outside of either method and don't pass it around at all... e.g.
String s = new String("AAAAA");
public void methodA() {
methodB();
System.out.println(s);
}
public void methodB() {
s = new String("BBBBB");
}
will also yield "BBBBB"
You can do it like this:
Instead of normally initializing it (like KreuzLagerort20kg = new ArrayList<Screws>();) in constructor, you do it in fillLager.
import java.util.ArrayList;
public class Lager {
private ArrayList<Screws> KreuzLagerort20kg,KreuzLagerort50kg;
public Lager(){
//KreuzLagerort20kg = new ArrayList<Screws>();
//KreuzLagerort50kg = new ArrayList<Screws>();
fillLager(1, 20);
fillLager(1, 50);
}
public void fillLager(int typ, int code){
if (code==20){
KreuzLagerort20kg = new ArrayList<Screws>();
}
if (code==50){
KreuzLagerort50kg = new ArrayList<Screws>();
}
// code that loops through combinations and adds them to the arraylist
}}}}}}
Related
This question already has answers here:
How do I test a class that has private methods, fields or inner classes?
(58 answers)
Closed 3 years ago.
private void ConvertString(ABC object)
{
String head = "";
String tail="string_tail";
if(!tail.isEmpty())
{
String converter = new StringConvert();
head = converter.convert(tail, TYPE1);
setHeadToTail(head,object);
}
}
private void setHeadToTail(String head, ABC object)
{
List<Mixture> values=object.getValues();
if (values!=null)
{
for (Mixture Values1 : values)
{
if (Values1 instanceof NumMixture)
{
((NumMixture) Values1 ).setTail(head);
}
}
}
}
I want to write unit test for ConvertString method to check weather the value 'head' converted is equal to the value 'head' being passed in setHeadToTail().
Can anyone help in this?
#Test
public void test_ConvertedValue() throws Exception {
ABC obj1=methodToSetSomeValues();
Method method=Project.class.getDeclaredMethod("ConvertString", ABC.class);
method.setAccessible(true);
method.invoke(new Project(), obj1);
String expectedVal= "1234";
ArgumentCaptor<String> argumentCaptor=ArgumentCaptor.forClass(String.class);
verifyPrivate(new Project()).invoke("setHeadToTail", argumentCaptor.capture(), obj1);
assertEquals(expectedVal,argumentCaptor.getValue());
}
In this test case I want to check the value of 'head' converted is equal to parameter passed in setHeadToTail() i.e. head but this is not working.
I had the same question when I first started out. Basically, you can view a private method as just code as if it wasn't in a method at all; it's just there to make your code more readable or to remove boilerplate. So if you want to test the functionality, you need to test the method which is calling it.
public void someMethod() { // test this
// some code
privateMethod();
// some more code
}
private void privateMethod() {
// some code
}
When unit testing someMethod(), act as if the contents of privateMethod() are not in any method at all.
edit: In your case, it doesn't matter how many nested private methods you have, test the non-private method calling them all as if it were 1 large block of code.
This question already has answers here:
Is there a way to compare lambdas?
(3 answers)
Closed 7 years ago.
I am not sure how I can be sure about equality/immutability of functional interface.
I guess there might be no way to assure equality when I use this syntactic sugar in java 8, please let me know any hint if you have any.
I made a short code snippet for my question.
public interface Element {
void doSomething(int a);
}
and I've tried to add instance of this interface in functional way
public class FunctionSet {
public void doubleUp(int a) {
System.out.println(a*2);
}
public void square(int a) {
System.out.println(a*a);
}
public static void main(String[] args) {
HashSet<Element> set = new HashSet<>();
FunctionSet functionSet = new FunctionSet();
set.add(functionSet::doubleUp);
set.add(functionSet::square);
System.out.println(set.add(functionSet::doubleUp));
}
}
it prints true which means there were not any equality check and also I can't remove any instance from Set once I add it.
in case I use functional interface as an argument, Is there any way that I can compare those instance somehow?
will appreciate any help, thanks in advance!
You can store your method reference into a variable:
public static void main(String[] args) {
HashSet<Element> set = new HashSet<>();
FunctionSet functionSet = new FunctionSet();
Element fn = functionSet::doubleUp;
set.add(fn);
set.add(functionSet::square);
System.out.println(set.add(fn));
}
This way it returns false.
When you create the same labmda or method reference in different code locations, it's roughly the same as you would create a new anonymous class in both positions:
public static void main(String[] args) {
HashSet<Element> set = new HashSet<>();
FunctionSet functionSet = new FunctionSet();
set.add(new Element() {
#Override
public void doSomething(int a) {
functionSet.doubleUp(a);
}
});
set.add(new Element() {
#Override
public void doSomething(int a) {
functionSet.square(a);
}
});
System.out.println(set.add(new Element() {
#Override
public void doSomething(int a) {
functionSet.doubleUp(a);
}
}));
}
So every time it's a different object, though it may look the same. For every encountered method reference separate anonymous class is created at the runtime:
Element e1 = functionSet::doubleUp;
Element e2 = functionSet::doubleUp;
System.out.println(e1.getClass());
System.out.println(e2.getClass());
The output will be like this:
class FunctionSet$$Lambda$1/918221580
class FunctionSet$$Lambda$2/1554547125
So practically it's two distinct objects of two distinct classes. It would be quite difficult to conclude that they do the same thing without comparing their bytecode. Also note that they both capture the functionSet variable, so it should also be ensured that it wasn't changed between two method references.
The only workaround I can think up is to declare all the method references as constants in your code and later reference them instead of using method references directly:
public static final Element FN_DOUBLE_UP = new FunctionSet()::doubleUp;
public static final Element FN_SQUARE = new FunctionSet()::square;
public static void main(String[] args) {
HashSet<Element> set = new HashSet<>();
set.add(FN_DOUBLE_UP);
set.add(FN_SQUARE);
System.out.println(set.add(FN_DOUBLE_UP));
}
This question already has answers here:
Is this a valid way to count instances of objects?
(2 answers)
Closed 9 years ago.
class Clasa {...}
class Test {
public static void main(String[] args){
Clasa x = new Clasa();
System.out.println(x.getNo());//displays 1
Clasa[] y = new Clasa[10];
for(int i = 0; i<4; i++)
y[i]=new Clasa();
System.out.println(y[0].getNo()); //displays 5
}
}
How can I replace those three dots, so GetNo() method call to return the number of instantiated objects of class Clasa. Test class should not be changed.
Add a static variable which acts as a counter and increment it inside the constructor and getNo returns the value of the static variable.
Static variable have their values kept across all instances of a class
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
}
I agree with Brian , on that the above code is not considering the GC. So I would like to replace your code with the below code snippet
package com.instance.main;
import com.instance.target.Clasa;
public class Test{
public static void main(String[] args) {
Clasa targetClass;
Object[] object=new Object[10];
for(int i=0;i<object.length;i++){
object[i]=new Clasa();
}
System.out.println("Number of Instantiate Object {Before Calling GC}: "+Clasa .getNumberOfInstatiateObj());
/* Here I am trying to deallocate the memory of Object at index no 9, so that GC called this unused object to deallocate it from memory*/
for(int i=0;i<object.length;i++){
if(i==8){
object[i]=object[i+1];
object[i+1]=null;
System.runFinalization();
System.gc();
}
}
}
}
just put the above code beneath the main method and also you have to modify your Clasa code from the below code
package com.instance.target;
class Clasa {
private static int nbInstances = 0;
public Clasa () {
nbInstances++;
}
public int getNo() {
return nbInstances;
}
public void finalize(){
nbInstances --;
System.out.println("Number of Instantiate Object {After Calling GC}: "+nbInstances );
}
}
After modifying your code by following the above steps , your code will give you your desired output.
Please let me correct if I am wrong some where.
Hi Dany I modified my code , so according to the above code ,you have to create your class under different package which written in the class code . And let me know if you are getting problem still.
This question already has answers here:
Java: How To Call Non Static Method From Main Method?
(9 answers)
Closed 9 years ago.
hello i whave an function which it take the number after the (.) and after "Vl" in string
so i want call this function on the code but they tell me this error
non-static method Ajuster(String) cannot be referenced from a static context
this the code
public class Test {
public Integer Ajuster(String data) {
Integer vlan=0;
if (data.indexOf("Vl") >= 0) {
int pos = data.indexOf("Vl") + 2;
String vl = data.substring(pos, data.length());
vlan=Integer.parseInt(vl.trim());
} else {
int pos = data.lastIndexOf(".") + 1;
String vl = data.substring(pos, data.length());
try {
vlan=Integer.parseInt(vl.trim());
} catch (Exception e) {
e.printStackTrace();
}
}
return vlan;
}
public static void main(String[] args) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/mohammedia", "root", "123456");
String sql = "SELECT * FROM router;";
Telnet_Interface telnet = new Telnet_Interface();
Telnet_Ressources telnet_R = new Telnet_Ressources();
Telnet_Interface telnet1 = new Telnet_Interface();
Telnet_Interface telnet2 = new Telnet_Interface();
PreparedStatement prest = conn.prepareStatement(sql);
ResultSet res=prest.executeQuery();
while(res.next()){
telnet1.Config(res.getString(1), "noc", "nocwana", res.getString(1));
telnet2.Config(res.getString(2), "noc", "nocwana", res.getString(2));
}
ArrayList myData=telnet.getMyData();
ArrayList myData1=telnet1.getMyData();
ArrayList myData2=telnet2.getMyData();
for(int i=0;i<myData1.size();i++)
{
String data1=myData1.get(i).toString();
Integer vl1=Ajuster(data1);
System.out.print(vl1);
}
}
}
so the problem it's about the line: Integer vl1=Ajuster(data1);
Thank you
main is static. It means that it is not related to a instance of the Test class, but to the class itself.
Ajuster (please follow Java coding guidelines, it should be ajuster) is not static, so it is related to an instance of Test. So, to use it you must use it from a created instance (like this)
Test test = new Test();
test.ajuster();
or make it static (try not to overuse static methods)
It seems you're calling the method public Integer Ajuster(String data) that is non-static from the main that's, in fact, static. In order to call that method Ajuster you must instantiate an object of the class Test.
I suppose you know how to do this, but however you must write this down Test test = new Test().
You cant call a non-staic without any object reference.
Either make the method static like (depends if it dont involve any instance varialbe)
public static Integer Ajuster(String data)
or invoke with a object of class Test like
Test obj = new Test();
obj.Ajuster("data");
or better this http://docs.oracle.com/javase/tutorial/
PS: Method starting with capital name looks really weird
You cannot call a non-static method with out creating an object. If it's a non-static context, however current object (this) will be there. If from static method you have to create an object and call the method on that object.
Static methods are all same for every object. In that case, we cannot know on what object are we applying the method or accessing a variable, that's why there is restriction.
Alternatively, you can make the method as static. But that depends. You should know when to use static methods and when not to use. It's a design issue.
Read:
To know the difference between static and non-static method
When should a method be static
How to call a non static method from main
So, create an object and call the method:
Test newTest = new Test();
newTest.ajuster();
You have to understand that non-static context cannot be referred in static context
public int test = 0;
public static void main(String[] args) {
test += 4; //this wont compile
}
Non-static context however can include both non-static and static contexts.
Try something like this.
public class Test {
public int test = 0;
public static void main(String[] args) {
new Test();
}
public Test() {
test += 4; //this will compile
}
}
If you cannot understand this, try to search and learn about Constructor
Ok this is a guess a really simple problem which I am having a black out about.... however it is killing my head.
Here is the source:
import java.util.Arrays;
public class InputValues {
public int[] myarrayvar;
public InputValues(int[] myarraypass) {
---- help here
}
public void init() {
---help here
}
public int[] getmyarrayvar() {
return myarrayvar;
}
public void setmyarrayvar(int[] myarraypass) {
this.myarrayvar= mayarraypass;
}
}
I call the this with
InputValues inputValues = new InputValues(myarraypass);
inputValues.init();
myarraypass is of type int[].
Like I said this should be really easy.... but I can't get it to work for some reason....
In case your myarrayvar is public then why would you need a setter and getter. You need them only when your member is inaccessible to the outside world, i.e. it's marked private.
Nest, you can use the following in your constructor for setting the array,
public InputValues(int[] myarraypass) {
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length );
}
You can try following things:
Change the instance variable access from public to private.
in constructor you can use following line:
this.myarrayvar = myarraypass;
But remember, if myarraypass is modified outside class InputValues, myarrayvar will also be affected.
If you don't want that behavior to occur, you should copy index-by-index.
this.myarrayvar = new int[myarraypass.length];
for(int i=0; i<myarraypass.length;i++)
this.myarrayvar[i] = myarraypass[i];
OR
this.myarrayvar = (int[]) myarraypass.clone();
OR
this.myarrayvar = new int[myarraypass.length];
System.arraycopy(myarraypass, 0, this.myarrayvar, 0, myarraypass.length);